Talk:Modulinos: Difference between revisions

(→‎Examples: Expanded needs for a modified task.)
(→‎Examples: Ruby.)
Line 184:
 
:: '''So, who's for the change!''' --[[User:Paddy3118|Paddy3118]] 08:15, 13 March 2011 (UTC)
 
----
Yes, I guess that it would be a good idea to change all the examples to hailstone libraries. Here is [[Ruby]] code. Might require Ruby 1.9.
 
<lang ruby># hailstone.rb
module Hailstone
def sequence(n)
seq = [n]
seq << (n = if n.even? then n / 2 else n * 3 + 1 end) until n == 1
seq
end
module_function :sequence
 
if __FILE__ == $0
big_hs = Enumerator.new do |y|
(1...100_000).each { |n| y << sequence(n) }
end.max_by { |hs| hs.size }
puts "#{big_hs[0]} has a hailstone sequence length of #{big_hs.size}."
puts "The largest number in that sequence is #{big_hs.max}."
end
end</lang>
 
<lang ruby># hsfreq.rb
require 'hailstone'
 
module Hailstone
def most_common_length(enum)
h = Hash.new(0)
enum.each { |n| h[sequence(n).length] += 1 }
h.max_by { |length, count| count }
end
module_function :most_common_length
 
if __FILE__ == $0
last = 99_999
length, count = most_common_length(1..last)
puts "Given the hailstone sequences for 1 to #{last},"
puts "the most common sequence length is #{length},"
puts "with #{count} such sequences."
end
end</lang>
 
<pre>$ ruby19 hailstone.rb
77031 has a hailstone sequence length of 351.
The largest number in that sequence is 21933016.
$ ruby19 -I. hsfreq.rb
Given the hailstone sequences for 1 to 99999,
the most common sequence length is 72,
with 1467 such sequences.</pre>
 
--[[User:Kernigh|Kernigh]] 04:16, 14 March 2011 (UTC)
Anonymous user