Here's the exercise:
You have been given a list of sequential numbers from 1 to 10,000, but they are all out of order; furthermore, a single number is missing from the list. The object of the task is to find out which number is missing.
The strategy to this problem is to sum the elements in the array, then sum the range 1 to 10,000, and subtract the difference. This is equal to the missing number. The formula for calculating the sum of the range from 1..n
being n(n+1)/2
.
This is my current approach:
def missing_number(array)
sum = 0
array.each do |element|
sum += element
end
((10000*10001)/2) - sum
end
Where I am getting tripped up is the output when I input an array such as this:
puts missing_number(*1..10000) #=> 0
Why does this happen?
Thanks!