Picking a random element from a Map

Hi,
how do I (quickly) pick a random element from a `Data.Map.Map`?
Right now I am using `head $ Map.keys p` to get the first element, but
I'd like to replace this by a random element.
I know I have to drag around the state of the random generator
somewhere, but if I have one I am wondering what's the best way to use
one to take a pick from the map.
Thanks
--
Harald Bögeholz

Hi Harald,
how do I (quickly) pick a random element from a `Data.Map.Map`?
Right now I am using `head $ Map.keys p` to get the first element, but I'd like to replace this by a random element.
I know I have to drag around the state of the random generator somewhere, but if I have one I am wondering what's the best way to use one to take a pick from the map.
M.keys map !! randomValue `mod` M.size map But if you need a high performance solution than it's more appropriate to put the values into a Data.Vector and indexing into it. Greetings, Daniel

Am 26.09.12 10:09, schrieb Daniel Trstenjak:
Hi Harald,
how do I (quickly) pick a random element from a `Data.Map.Map`?
[..]
M.keys map !! randomValue `mod` M.size map
But if you need a high performance solution than it's more appropriate to put the values into a Data.Vector and indexing into it.
I was hoping to find a solution that makes use of the specific structure
of a map, but now I have written it like this and it works for me:
let (r, gen') = randomR (0, Map.size m - 1) gen
in (Map.keys m !! r, gen')
Thanks for the hint!
Harald
--
Harald Bögeholz
participants (2)
-
Daniel Trstenjak
-
Harald Bögeholz