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.

import 'dart:math';
var x = m.values.toList()[Random().nextInt(m.length)];
def main(m) do
  m
  |> Map.values()
  |> Enum.random()
end
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")
}
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
}
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)]);
@vals = values %m;
$x = $vals[ int rand @vals ];
import random
x = random.choice(list(m.values()))
x = m.values.sample

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