Logo

Programming-Idioms

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

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 "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))
	for _, x := range m {
		if k == 0 {
			return x
		}
		k--
	}
	panic("unreachable")
}
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")
}

The type parameter K has a constraint: it must be comparable with ==
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")
}
var arr = m.Values.ToArray();
var x = arr[Random.Shared.NextInt64(0, arr.Length)];

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