1

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?

0

2 Answers 2

1

You can use this code.

If n is 1 return it like Array. If n % 2 == 0 use n / 2 else use (3 * n) + 1. if n is now 1 return it like Array else define new Array with n value and call yourself with new n.

def collatz(n)
  return [n] if n == 1
  n = n % 2 == 0 ? n / 2 : (3 * n) + 1
  n == 1 ? [n] : [n] + send(__method__, n)
end

output

p collatz(10)
# => [5, 16, 8, 4, 2, 1]

I hope this helps

Sign up to request clarification or add additional context in comments.

Comments

0

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!

and within recurse:

def collatz(n)
  arr = []
  loop do
    n = n % 2 == 0 ? n / 2 : (3 * n) + 1
    arr << n
    break if n == 1
  end
  arr
end

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

2 Comments

Why is recurse evil?
recurse is evil because it limit your abilities with maximum call stack limitations. It (callstack limit) depends on your language and computer, but it not infinite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.