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.
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.
?>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With