Created
September 11, 2015 06:17
-
-
Save rvalenciano/ae0a27291f148de7520a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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