On Thu, Oct 10, 2013 at 7:22 PM, Green E. [email protected] wrote:
there should be a different result
But then it’s not shuffle any more, is it? You basically associate a
particular order with a number as key. I can think of two approaches:
- manipulate the random generator via the seed:
irb(main):001:0> a = (1…5).to_a
=> [1, 2, 3, 4, 5]
irb(main):002:0> srand 0
=> 38759114252116045413516501677716616995
irb(main):003:0> a.shuffle
=> [1, 4, 2, 5, 3]
irb(main):004:0> srand 0
=> 0
irb(main):005:0> a.shuffle
=> [1, 4, 2, 5, 3]
irb(main):006:0> srand 4
=> 0
irb(main):007:0> a.shuffle
=> [1, 2, 4, 3, 5]
irb(main):008:0> srand 4
=> 4
irb(main):009:0> a.shuffle
=> [1, 2, 4, 3, 5]
- use a Hash to store the fixed relation:
irb(main):011:0> a = (1…5).to_a
=> [1, 2, 3, 4, 5]
irb(main):012:0> cache = Hash.new {|h,k| h[k] = a.shuffle}
=> {}
irb(main):013:0> cache[0]
=> [5, 3, 1, 4, 2]
irb(main):014:0> cache[0]
=> [5, 3, 1, 4, 2]
irb(main):015:0> cache[5]
=> [5, 2, 3, 1, 4]
irb(main):016:0> cache[5]
=> [5, 2, 3, 1, 4]
irb(main):017:0> cache[5]
=> [5, 2, 3, 1, 4]
irb(main):018:0> cache[2]
=> [5, 4, 2, 1, 3]
irb(main):019:0> cache[2]
=> [5, 4, 2, 1, 3]
irb(main):020:0> cache
=> {0=>[5, 3, 1, 4, 2], 5=>[5, 2, 3, 1, 4], 2=>[5, 4, 2, 1, 3]}
I’d prefer approach 2 because that does not have side effects on other
parts of the program which want to generate random numbers.
Kind regards
robert