IliasP
IliasP

Reputation: 91

Find number of missing numbers to complete consecutive array

I am trying to write a function that gives you the number of numbers need to complete a consecutive array. For example if we have the array [3,5,7] the function should return 2 (i.e. 4,6). I have come up with the code below but it gives me the following error? Any ideas why? Thanks!

    def consecutive(*arr)

      sorted = arr.sort
      current_count = 0

      sorted.each_index do |i| 
        next if i == sorted.length
        difference = arr[i+1] - arr[i] - 1
        current_count += difference
      end 

      current_count
    end

And this is the error:

   undefined method `-' for nil:NilClass
   (repl):9:in `block in Consecutive'
   (repl):6:in `each_index'
   (repl):6:in `Consecutive'
   (repl):16:in `<main>'

Upvotes: 1

Views: 179

Answers (2)

seph
seph

Reputation: 6076

arr[i + 1] is going to be nil on your final pass through each_index. You can use each_cons(2) instead and have it deal with the indices for you:

def Consecutive(arr)
  sorted = arr.sort
  current_count = 0

  sorted.each_cons(2) do |a, b|
    difference = b - a - 1
    current_count += difference
  end 

  current_count
end

Consecutive([3,5,7])
 => 2 

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110675

If arr is your array, you can do this:

arr = [3,1,5,7,8]

f,l = arr.minmax
  #=> [1, 8] 
l-f+1 - arr.size
  #=> 3

Upvotes: 1

Related Questions