Logo

Programming-Idioms

  • Fortran
  • Rust

Idiom #250 Pick a random value from a map

Choose a value x from map m.
m must not be empty. Ignore the keys.

use rand::prelude::*;
let mut rng = rand::thread_rng();
let x = m.values().choose(&mut rng).expect("m is empty");
var arr = m.Values.ToArray();
var x = arr[Random.Shared.NextInt64(0, arr.Length)];

New implementation...
< >
programming-idioms.org