2015-12-11 18 views

risposta

13

Si desidera la cassa rand, in particolare il metodo choose.

// cargo-deps: rand="0.3.12" 
extern crate rand; 

use rand::Rng; 

fn main() { 
    let vs = vec![0, 1, 2, 3, 4]; 
    println!("{:?}", rand::thread_rng().choose(&vs)); 
} 
+0

vi ringrazio molto ! – coco

1

Se si vuole scegliere più di un elemento, che la cassa random_choice può essere il giusto per voi:

extern crate random_choice; 
use self::random_choice::random_choice; 

fn main() { 
    let mut samples = vec!["hi", "this", "is", "a", "test!"]; 
    let weights: Vec<f64> = vec![5.6, 7.8, 9.7, 1.1, 2.0]; 

    let number_choices = 100; 
    let choices = random_choice().random_choice_f64(&samples, &weights, number_choices); 

    for choice in choices { 
     print!("{}, ", choice); 
    } 
} 
1

Utilizzando rand::sample:

use rand::{thread_rng, sample}; 

let mut rng = thread_rng(); 
let mut samples = vec!["hi", "this", "is", "a", "test!"]; 
let sample = sample(&mut rng, samples, 1); 
println!("{:?}", sample); 
Problemi correlati