Reputation: 34013
I have collections of items (ActiveRecord_AssociationRelation).
I need to randomly pick one item from each collection, but it should pick the same item the second and third time etc.
I'm thinking of some kind of one way algorithm, like hashing. E.g. perhaps based on the length of the collection, let's say 50, it will always generate the number 34.
Any idea how I could accomplish this?
Upvotes: 0
Views: 836
Reputation: 80065
The Array sample
method takes a Random Number Generator as a (named) argument, so you can do:
rng = Random.new(8) # The seed (8) is just a meaningles number.
a = ("a".."z").to_a
p a.sample(random: rng) # "d"
p a.sample(random: rng) # "u"
The next time it will result in "d" and "u" again.
If a repeatable random sequence is needed, all you need is a seeded Random number generator
rng2 = Random.new(10)
num = rng2.rand(collection.size)
Upvotes: 4