Skip to content

Instantly share code, notes, and snippets.

@KAllan357
Created April 28, 2011 22:02
Show Gist options
  • Save KAllan357/947448 to your computer and use it in GitHub Desktop.
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.
#!/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