0

This code is not working. I'm trying to code the Collatz conjecture but the code only seems to run once for the input 8. It prints out 4, 1 ,1 and so that shows it only runs for one step. The else block is never executed either. Can someone tell me what's wrong with this Ruby code? I have no idea why it's not working the way it's supposed to.

class Collatz
    def collatz(number)
      if number == 1
         return 0
      end
      steps = 0
      while number > 1 do
         if number % 2 == 0 
           number = number / 2
           puts number
           steps = steps + 1
           puts steps
         else
           number = (number * 3) + 1
           puts number
           steps = steps + 1
           puts steps
      end  
      return steps
    end
end

steps = Collatz.new.collatz(8)
puts steps
end

2 Answers 2

1

You have a return statement that's terminating execution after the first iteration of the while loop.

Try

class Collatz
  def collatz(number)
    return 0 if number == 1

    steps = 0
    while number > 1 do
      if number % 2 == 0
        puts number /= 2
        puts steps += 1
      else
        number = (number * 3) + 1
        puts number
        puts steps += 1
      end
    end

    return steps
  end
end

steps = Collatz.new.collatz(8)
puts steps

which returns 3 and prints

4
1
2
2
1
3

[Finished in 0.4s]

And if you want to make your code a little cleaner and more idiomatic, you could refactor it as follows:

class Collatz
  def collatz(number)
    return 0 if number == 1

    steps = 0
    while number > 1
      number = number.even? ? number / 2 : (number * 3) + 1
      puts number, steps += 1
    end

    steps
  end
end

steps = Collatz.new.collatz(8)
#4
#1
#2
#2
#1
#3
#=> 3
Sign up to request clarification or add additional context in comments.

Comments

0

Let's properly indent your code and see if we can find the problem:

class Collatz
  def collatz(number)
    if number == 1
      return 0
    end
    steps = 0
    while number > 1 do
      if number % 2 == 0 
        number = number / 2
        puts number
        steps = steps + 1
        puts steps
      else
        number = (number * 3) + 1
        puts number
        steps = steps + 1
        puts steps
      end  
      return steps
    end
  end
  steps = Collatz.new.collatz(8)
  puts steps
end

Look at that — the return is in your while-loop, so it returns at the end of the first iteration. It looks like you actually wanted to end your while loop on the line above that.

This one of the reasons why coding style is really important. It can trick you into thinking your code means something it doesn't.

Comments

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.