Skip to content

Instantly share code, notes, and snippets.

@DSpeckhals
Created December 17, 2014 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DSpeckhals/bfa3ff78eb982e609c09 to your computer and use it in GitHub Desktop.
Save DSpeckhals/bfa3ff78eb982e609c09 to your computer and use it in GitHub Desktop.
Find the missing number
/* 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