Created
December 17, 2014 21:44
-
-
Save DSpeckhals/bfa3ff78eb982e609c09 to your computer and use it in GitHub Desktop.
Find the missing number
This file contains hidden or 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
/* You've probably seen those goofy comments in forums that say "find the | |
* missing number in a list of 10,000 numbers. Who wants to take time to | |
* do that? I know there are arithmetical solutions to this problem, but | |
* I thought I'd find a simple functional approach to this. | |
* | |
* This snippet simply takes the array of numbers (expected to be unsorted, | |
* but either will work), sorts them, then uses the reduce function to compare | |
* to the previous value in the array. I like this method more than summing | |
* all numbers, dividing by two, comparing, blah, blah. The map function works | |
* great! | |
*/ | |
[1, 5, 3, 2].sort(function(a, b) { | |
return a - b; | |
}).reduce(function(previous, current) { | |
current !== previous + 1 && console.log(current - 1); | |
return current; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment