I am working on Collatz Conjecture in Ruby and stop at n = 1. This is the code that I have so far:
def collatz(n)
arr = []
if n == 1
arr << n
return arr
elsif n % 2 == 0
n = n / 2
arr << n
collatz(n)
else
n = (3 * n) + 1
arr << n
collatz(n)
end
end
I want the code to return an array of all n values throughout the loop.
For example, if I do collatz(10), I wish it to display [5,16,8,4,2,1]
Right now it displays [1] for any input value. This is because after the first loop, it calls collatz(n), and the first line says arr= [], thereby resetting my array each loop.
How can I continue the method loop while appending my array?