Iggy Iggy - 5 months ago 15
Ruby Question

Appending array while using recursive loop in Ruby

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?

Answer

add array to params as exampled:

def collatz(arr, n)
  if n == 1
    arr << n
    return arr
  elsif n % 2 == 0
    n = n / 2
    arr << n
    collatz(arr, n)
  else
    n = (3 * n) + 1
    arr << n
    collatz(arr, n)
  end
end

puts "#{collatz([], 10).join(', ')}"

result will the same as you wish:

[5, 16, 8, 4, 2, 1, 1]

But remember: recurse is a evil!