1# The module for the Collatz conjecture needed functions
2module RosettaCollatz
3 VERSION = "0.1.0"
4
5 # Returns the collatz number of `a`
6 #
7 # If `a` is even, divide it by 2. Otherwise, multiply 3 by `a`, and
8 # add 1.
9 def self.collatz(a)
10 if a % 2 == 0
11 a // 2
12 else
13 3 * a + 1
14 end
15 end
16
17 # Returns a sequence of collatz integers starting from a.
18 def self.collatz_sequence(a)
19 result = "#{a}: "
20 i = a
21 while i >= 1
22 if i == 1
23 result = result + "1"
24 break
25 end
26 result = result + "#{i}, "
27 i = collatz(i)
28 end
29 result
30 end
31end
32
33sequence = Array.new(10000) { |i| Collatz.collatz_sequence(i + 1) }
34puts (sequence.reduce("") { |acc, i| "#{acc}\n" + "#{i}" })