Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
Select your favorite languages :
  • Or search :

Idiom #250 Pick a random value from a map

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

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")
}
// Objects
const values = Object.values(m);

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

const x = values[~~(Math.random() * values.length)]
uses fgl;
x := m.Data[Random(m.Count)]);
import random
x = random.choice(list(m.values()))
x = m.values.sample

New implementation...
programming-idioms.org