views:

75

answers:

1

The Random class in Ruby 1.9.2 is guaranteed to generate random numbers in the same order, given a particular seed and range. For instance:

r = Random.new(23)
r.rand(100)         # 83
r.rand(100)         # 40

But suppose I want to generate the next number in the sequence on another computer (without re-generating the earlier numbers in the sequence). This should be possible, given the previous output. Is there a way to do this with the Random class? Or do I have to write my own implementation of the Mersenne twister?

A: 

Can't test, but the generator can be marshalled, according to Marc-André Lafortune here. So this might work:

r = Random.new(23)
r.rand(100)         # 83
r.rand(100)         # 40

File.open("/path/to/file","w") do |f|
  Marshal.dump(r,f)
end

# later, may be on another computer

File.open("/path/to/file","r") do |f|
  @v = Marshal.load(f)
end

puts @v.rand(100)
steenslag
That might work, but that seems awfully inefficient. In principle, you should only need to transmit the most recently generated value from one computer to the other; you shouldn't have to serialize the whole object.
Trevor Burnham