On Wed, 12 Mar 2003, Martin DeMello wrote: > Given a stream of numbers that, at some point, recurs with period k, > find k. > > Harder: as before, but with a prefix of m nonrepeating digits before the > cycle sets in. Sounds like some statistics is applicable. Here's my take that returns the position of the second greatest maximum of the cyclic autocorrelation: def find_k(signal) autocorr = cyclic_autocorrelation(signal)[1..-1] autocorr.index(autocorr.max) + 1 end def cyclic_autocorrelation(signal) (0...signal.size).map{|i| scalar_product(signal, signal[i..-1] + signal[0...i]) } end def scalar_product(v1, v2) sum = 0 (0...v1.size).each{|i| sum += v1.at(i) * v2.at(i)} sum end if (__FILE__==$0) puts(find_k(ARGV.map{|a| a.to_f})) # replace with to_i if sufficient end Then run: $ ruby findk.rb 3 4 5 6 7 1 0 3 1 0 3 1 0 3 1 0 3 1 0 3 1 0 3 1 0 3 1 3 T