Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I randomly select one element from a vector or array?

Tags:

rust

I have a vector where the element is a (String, String). How can I randomly pick one of these elements?

like image 366
coco Avatar asked Dec 11 '15 02:12

coco


People also ask

How do you access a specific element in a vector?

Element access:reference operator [g] – Returns a reference to the element at position 'g' in the vector. at(g) – Returns a reference to the element at position 'g' in the vector. front() – Returns a reference to the first element in the vector. back() – Returns a reference to the last element in the vector.

How do you select a random value from a vector in R?

1 Answer. There could be many ways to randomly select elements from an R vector. You can use the sample() or the runif() function to select elements from the vector.

How do you generate a random value from a vector in C++?

To generate the random values between 0 and n-1 , we can use the cstdlib's functions rand() and srand() or use any of the standard generators defined in the <random> header introduced in C++11.


3 Answers

You want the rand crate, specifically the choose method.

use rand::seq::SliceRandom; // 0.7.2

fn main() {
    let vs = vec![0, 1, 2, 3, 4];
    println!("{:?}", vs.choose(&mut rand::thread_rng()));
}
like image 124
DK. Avatar answered Oct 17 '22 10:10

DK.


Using choose_multiple:

use rand::seq::SliceRandom; // 0.7.2

fn main() {
    let samples = vec!["hi", "this", "is", "a", "test!"];
    let sample: Vec<_> = samples
        .choose_multiple(&mut rand::thread_rng(), 1)
        .collect();
    println!("{:?}", sample);
}
like image 16
Afshin Mehrabani Avatar answered Oct 17 '22 11:10

Afshin Mehrabani


Another choice for weighted sampling that is already included in the rand crate is WeightedIndex, which has an example:

use rand::prelude::*;
use rand::distributions::WeightedIndex;

let choices = ['a', 'b', 'c'];
let weights = [2,   1,   1];
let dist = WeightedIndex::new(&weights).unwrap();
let mut rng = thread_rng();
for _ in 0..100 {
    // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c'
    println!("{}", choices[dist.sample(&mut rng)]);
}

let items = [('a', 0), ('b', 3), ('c', 7)];
let dist2 = WeightedIndex::new(items.iter().map(|item| item.1)).unwrap();
for _ in 0..100 {
    // 0% chance to print 'a', 30% chance to print 'b', 70% chance to print 'c'
    println!("{}", items[dist2.sample(&mut rng)].0);
}
like image 12
xji Avatar answered Oct 17 '22 10:10

xji