Skip to content

Instantly share code, notes, and snippets.

@rvalenciano
Created September 11, 2015 06:17
Show Gist options
  • Save rvalenciano/ae0a27291f148de7520a to your computer and use it in GitHub Desktop.
Save rvalenciano/ae0a27291f148de7520a to your computer and use it in GitHub Desktop.
def consecutive(arr)
#your code here
min_numbers = 0
if arr.size > 1
arr.sort!
arr.each_with_index do |item, index|
if index != (arr.size - 1)
min_numbers = min_numbers + ((arr[index+1] - arr[index]) - 1 )
end
end
end
min_numbers
end
@rvalenciano
Copy link
Author

Description

Create the function consecutive(arr) that takes an array of integers and return the minimum number of integers needed to make the contents of arr consecutive from the lowest number to the highest number.

For example:
If arr contains [4, 8, 6] then the output should be 2 because two numbers need to be added to the array (5 and 7) to make it a consecutive array of numbers from 4 to 8. Numbers in arr will be unique.

Test cases

Test.assert_equals(consecutive([4,8,6]),2)
Test.assert_equals(consecutive([1,2,3,4]),0)
Test.assert_equals(consecutive([]),0)
Test.assert_equals(consecutive([1]),0)
Test.assert_equals(consecutive([-10]),0)
Test.assert_equals(consecutive([1,-1]),1)
Test.assert_equals(consecutive([-10,-9]),0)
Test.assert_equals(consecutive([0]),0)
Test.assert_equals(consecutive([10,-10]),19)
Test.assert_equals(consecutive([-10,10]),19)

Elegant Solution

def consecutive(arr)
  return 0 if arr.size == 0
  (arr.max - arr.min + 1) - arr.size
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment