Random element from a map

329 views
Skip to first unread message

glantucan con golo lojo

unread,
Aug 28, 2013, 9:17:45 AM8/28/13
to haxe...@googlegroups.com
What's the best way to get a random element out of a map?

Jason O'Neil

unread,
Aug 28, 2013, 9:33:55 AM8/28/13
to haxe...@googlegroups.com

var array = Lambda.array(myMap);
var key = Math.floor(Math.random()*array.length);
var item = array[ key ];

Or use my stupidly simple library, http://lib.haxe.org/p/random/

Random.fromIterable( myMap )

On 28/08/2013 9:17 PM, "glantucan con golo lojo" <glan...@gmail.com> wrote:
What's the best way to get a random element out of a map?

--
To post to this group haxe...@googlegroups.com
http://groups.google.com/group/haxelang?hl=en
---
You received this message because you are subscribed to the Google Groups "Haxe" group.
For more options, visit https://groups.google.com/groups/opt_out.

TopHattedCoder

unread,
Aug 28, 2013, 9:52:24 AM8/28/13
to haxe...@googlegroups.com
Smallest:
var arr = Lambda.array(map); // Convert the map values into an array
return arr[Std.random(arr.length)]; // Return a random element from the arrau

glantucan con golo lojo

unread,
Aug 28, 2013, 11:01:16 AM8/28/13
to haxe...@googlegroups.com
Nice!
Thank you both.
Just curious, besides Math.random() retrieving a float between 0 an 1 and Std.random(max) an integer between 0 and max. Is there another difference? One more random than another perhaps ;) ?

Juraj Kirchheim

unread,
Aug 28, 2013, 11:34:09 AM8/28/13
to haxe...@googlegroups.com
You can look through the different implementations. On most platforms
you will find Std.random is simply implemented on top of Math.random -
purely for convenience.

It seems that cpp is an exception:
https://github.com/HaxeFoundation/haxe/blob/development/std/cpp/_std/Std.hx#L49
Although it's still possible that they are using the same underlying generator.

Regards,
Juraj
Reply all
Reply to author
Forward
0 new messages