Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
var arr = m.Values.ToArray();
var x = arr[Random.Shared.NextInt64(0, arr.Length)];
def main(m) do
m
|> Map.values()
|> Enum.random()
end
m is not reused.
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")
}
The type parameter K has a constraint: it must be comparable with ==
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")
}
// Objects
const values = Object.values(m);
// Maps
const values = [...m.values()];
const x = values[~~(Math.random() * values.length)]
This converts the values of m into an array first, because you cannot get a random element from an object or a map.
int i = new Random().nextInt(m.size());
V x = new ArrayList<>(m.values()).get(i);
@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.
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.