From: Bill Kelly Date: 2008-08-18T09:18:10+09:00 Subject: Re: [QUIZ] Not So Random (#173) Here's a "cheater" solution. The sequences _are_ reproducible via the #reset / #next API, for as long as a given instance of the Random object remains in existence. However, independent instances of the Random object, even if started with the same seed, won't produce identical sequences. Probably too stupid to post, but oh well..... :) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class Random def initialize(ceiling=0, seed=nil) @ceiling = ceiling @seq = [] @idx = 0 srand(seed || (rand(0xFFFFFFFF) + 1)) end def next unless @idx < @seq.length @seq.push( rand(@ceiling) ) @idx = @seq.length - 1 end n = @seq[@idx] @idx += 1 n end def reset @idx = 0 end end if $0 == __FILE__ require 'test/unit' class RandomTest < Test::Unit::TestCase def test_001 x = Random.new(100) y = Random.new(1000) xseq = Array.new(5) { x.next } yseq = Array.new(5) { y.next } xseq += Array.new(5) { x.next } yseq += Array.new(5) { y.next } x.reset assert_equal( xseq, Array.new(10) { x.next } ) y.reset assert_equal( yseq, Array.new(10) { y.next } ) xseq += Array.new(5) { x.next } yseq += Array.new(5) { y.next } x.reset assert_equal( xseq, Array.new(15) { x.next } ) y.reset assert_equal( yseq, Array.new(15) { y.next } ) end end end ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Regards, Bill