Question

I'm trying to find the length of this collatz sequence. If I change test_array << number to puts number, I'm able to output each of the numbers in the sequence but for some reason, I cannot get this function to push the number into the array before returning a new value into the function. Any help would be much appreciated.

test_array = []

def collatz_sequence(number)
  return number if number==1
  if number%2==0
    test_array << number
    return collatz_sequence(number/2)
  else
    test_array << number
    return collatz_sequence(3*number+1)

 end
end

puts collatz_sequence(13)
Was it helpful?

Solution 2

A local variable cannot take a scope beyond a method definition. Use an instance variable instead.

@test_array = []

def collatz_sequence(number)
  return 1 if number == 1
  @test_array << number
  collatz_sequence(number.even? ? number / 2 : 3 * number + 1)
end

collatz_sequence(13) # => 1
@test_array # => [13, 40, 20, 10, 5, 16, 8, 4, 2]

But I don't see much point in returning 1 at the end. Including that in @test_array makes more sense:

@test_array = []

def collatz_sequence(number)
  @test_array << number
  collatz_sequence(number.even? ? number / 2 : 3 * number + 1) unless number == 1
end

collatz_sequence(13)
@test_array # => [13, 40, 20, 10, 5, 16, 8, 4, 2, 1]

But this is not a good practice because the array and the procedure of the method have dependency. A better way to do it is:

def collatz_sequence(number, test_array = [])
  return if number == 1
  collatz_sequence(number.even? ? number / 2 : 3 * number + 1, test_array)
end

collatz_sequence(13)

OTHER TIPS

test_array = [] is out of scope. def creates a new scope so you cannot access the value of test_array from within the method.

One way around this is to make test_array an instance variable: @test_array

what about this implementation:

    def collatz_sequence(number)
      array = [number]
      if number%2==0
        array += collatz_sequence(number/2)
      elsif number != 1
        array += collatz_sequence(3*number+1)
      end
      return array
    end

    puts collatz_sequence(13)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top