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!
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
undefined method `-' for nil:NilClass
(repl):9:in `block in Consecutive'
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