どうも、ちょげ(@chogetarou)です。
Vec(ベクタ)の要素をランダムに取得する方法を紹介します。
方法

Vec(ベクタ)の要素をランダムに取得するには、choose()とthread_rng()を使います。
まず、必要なモジュールをインポートします。
use rand::seq::SliceRandom;
次に、Vec(ベクタ)からchoose()を呼び出します。
choose()の引数に「&mut rand::thread_rng()
」を指定します。
最後にchoose()からunwrap()を呼び出します。
//vect=対象のベクタ
vect.choose(&mut rand::thread_rng()).unwrap();
上記のchoose()は、呼び出したVec(ベクタ)の要素をランダムに取得します。
rand::seq::SliceRandom - Rust
API documentation for the Rust `SliceRandom` trait in crate `rand`.
rand::thread_rng - Rust
API documentation for the Rust `thread_rng` fn in crate `rand`.
使用例
use rand::seq::SliceRandom;
fn main(){
let num = vec![1, 2, 3, 4, 5];
for _ in 0..5 {
println!("{:?}", num.choose(&mut rand::thread_rng()).unwrap());
}
}
出力:
1
1
2
5
3
コメント