0

Learning Ruby and trying out problems on Coderbyte. This code is supposed to find the number of numbers between numbers in an array. So [4,8,6] should return 2 (it needs 5 and 7 to be consecutive). [5,10,15] should return 8 and [-2,10,4] should return 10.

My solution is to get the difference between a number and its next greatest number, minus one, which is how many numbers are between them.

When I p new_arr inside my each loop, it has the correct array: [1,1] in the first case, [4,4] in the next case and [5,5] in the last case. But when I exit the each loop, the array is empty again and new_arr.reduce(:+) returns nil.

I can't understand why because I defined new_arr outside the each loop. Is there some scope issue I'm missing here?

def Consecutive(arr)

  arr.sort!
  num_of_nums = 0
  new_arr = []
  i = 0
  arr.each do
    return if i == arr.length - 1
    num_of_nums = (arr[i+1] - arr[i]) - 1
    new_arr << num_of_nums
    i+=1
    p new_arr
  end
  new_arr.reduce(:+)
end

2 Answers 2

1

You are not returning anything if i == arr.length - 1.

You probably want to return this value:

return new_arr.reduce(:+) if i == arr.length - 1

or use break instead of return, so you just break out of the innermost loop.

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

1 Comment

Thanks! This actually helped me solve a bug in another problem as well where I didn't properly understand the difference between return and break.
1

Your code doesn't work mainly because of the line return if i == arr.length - 1. You want to break out of the loop, but you are actually returning out of the method, which is not what you want.

I think you are a bit confused about how to use the each method, because you are also using an iterator (i) unnecessarily. Your code would be better with the each_with_index method. I think there is a better approach, though.

What we really want to do is find all the numbers in (arr[0]..arr[-1]).to_a that aren't in arr, right?

arr.sort!
((arr[0]..arr[-1]).to_a - arr).count

That will give you the number of numbers between the lowest number in the array (arr[0] after it is sorted) and the highest number in the array (arr[-1] after it is sorted) that aren't in the original array.

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.