Created
April 28, 2011 22:02
-
-
Save KAllan357/947448 to your computer and use it in GitHub Desktop.
Accepts an array of integers from 1-N in which one number is missing. N is equal to the length of the array minus 1.
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
#!/usr/local/bin/groovy | |
def findMissingNumber(def a) { | |
lowerSum = a.inject(0, { | |
sum, it -> sum += it | |
}) | |
upperSum = (1..(a.size + 1)).inject(0, { | |
sum, it -> sum += it | |
}) | |
return upperSum - lowerSum | |
} | |
assert findMissingNumber([1, 2, 3, 5]) == 4 | |
assert findMissingNumber([4, 3, 5, 2]) == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment