2015-12-11 24 views

Odpowiedz

13

Chcesz skrzynkę rand, w szczególności metodę 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

bardzo dziękuję ! – coco

1

Jeśli chcesz wybrać więcej niż jeden element, niż skrzyni random_choice może być właśnie dla Ciebie:

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

Korzystanie 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); 
Powiązane problemy