Logo

Programming-Idioms

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

Idiom #250 Pick a random value from a map

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

def main(m) do
  m
  |> Map.values()
  |> Enum.random()
end
import 'dart:math';
var x = m.values.toList()[Random().nextInt(m.length)];
import "math/rand"
func pick(m map[K]V) V {
	k := rand.Intn(len(m))
	i := 0
	for _, x := range m {
		if i == k {
			return x
		}
		i++
	}
	panic("unreachable")
}
import "math/rand"
func pick(m map[K]V) V {
	k := rand.Intn(len(m))
	for _, x := range m {
		if k == 0 {
			return x
		}
		k--
	}
	panic("unreachable")
}
import "sync"

var mu sync.RWMutex

func pick(m map[int]any) any {
	mu.RLock()
	defer mu.RUnlock()
	for _, v := range m {
		return v
	}
	return nil
}
func pick[K comparable, V any](m map[K]V) V {
	k := rand.Intn(len(m))
	i := 0
	for _, x := range m {
		if i == k {
			return x
		}
		i++
	}
	panic("unreachable")
}
// Objects
const values = Object.values(m);

// Maps
const values = [...m.values()];

const x = values[~~(Math.random() * values.length)]
import java.util.ArrayList;
import java.util.Random;
int i = new Random().nextInt(m.size());
V x = new ArrayList<>(m.values()).get(i);
uses fgl;
x := m.Data[Random(m.Count)]);
@vals = values %m;
$x = $vals[ int rand @vals ];
import random
x = random.choice(list(m.values()))
x = m.values.sample
use rand::prelude::*;
let mut rng = rand::thread_rng();
let x = m.values().choose(&mut rng).expect("m is empty");

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