Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reproduce random array sort

I have an array of objects that I want to sort by random. For this case I can use array.shuffle. But what if I want to reproduce that order later on the same array? Is there any way that I can provide a seed, random number, whatever, so that I can reproduce this sequence later?

I want to generate a random list of objects from a MongoDB database (using MongoID), and that list has to be reproduced later. But as far as I know, there is no really good way, to implement a random sort directly in MongoDB. There could be a lot of objects (>1,000,000), but computation time is for the first try not the fact that matters.

like image 497
23tux Avatar asked Apr 12 '13 15:04

23tux


2 Answers

If you look at the Ruby docs for Array#shuffle you'll see you can pass a Random as the generator; if you pass a new Random to shuffle using the same seed each time, it'll give the same results.

>> arr = %w{John Paul George Ringo}
=> ["John", "Paul", "George", "Ringo"]
>> arr.shuffle(random: Random.new(1))
=> ["Ringo", "John", "George", "Paul"]
>> arr.shuffle(random: Random.new(1))
=> ["Ringo", "John", "George", "Paul"]
>> arr.shuffle(random: Random.new(1))
=> ["Ringo", "John", "George", "Paul"]

Edit: This can be extended to have Array#shuffle produce multiple repeatable shufflings, so that both each individual shuffle and the sequence of shufflings can be repeated, by using one Random (rather than a new one each time) and renewing it with the same seed to repeat:

>> arr = [1, 2, 3, 4] => [1, 2, 3, 4]
>> r = Random.new(17) => #<Random:0x000000017be4d0>
>> arr.shuffle(random: r) => [3, 1, 4, 2]
>> arr.shuffle(random: r) => [1, 3, 2, 4]
>> arr.shuffle(random: r) => [4, 3, 2, 1]
>> r = Random.new(17) => #<Random:0x00000001c60da8>
>> arr.shuffle(random: r) => [3, 1, 4, 2]
>> arr.shuffle(random: r) => [1, 3, 2, 4]
>> arr.shuffle(random: r) => [4, 3, 2, 1]
>> etc.
?> 
like image 123
Reinstate Monica -- notmaynard Avatar answered Nov 11 '22 15:11

Reinstate Monica -- notmaynard


From looking at the source of the method (http://ruby-doc.org/core-2.0/Array.html#method-i-shuffle), it looks like it's dropping into the Ruby random number generator to sort.

If it is, you can set the seed with

srand *seed number*

before running the script. I'm not 100% on this though, it seems to work, but I'd certainly write unit tests for it!

like image 33
Joe Pym Avatar answered Nov 11 '22 15:11

Joe Pym