Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #250 Pick a random value from a map

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

@vals = values %m;
$x = $vals[ int rand @vals ];

The values operation extracts the values of a map (perl hash) into a perl list we call @vals.

The rand operator generates a random (real) number between 0 and the integer argument. In a scalar context, @vals is the length of the list.

We then truncate the decimal portion with int and use the result as an index into the @vals list.
var arr = m.Values.ToArray();
var x = arr[Random.Shared.NextInt64(0, arr.Length)];

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