Skip to content

Instantly share code, notes, and snippets.

@pklauzinski
Last active November 28, 2016 01:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pklauzinski/c50427f0b992286419f7 to your computer and use it in GitHub Desktop.
Save pklauzinski/c50427f0b992286419f7 to your computer and use it in GitHub Desktop.
Returns true if any two numbers in given array add up to given integer. This was a "live" coding question I was given in an interview.
/**
* Returns true if any two numbers in list add up to num
*/
function sumTwoMatch(list, num) {
var i = 0,
match = false,
list2;
for (; i < list.length; i++) {
list2 = list.slice();
list2.splice(i, 1);
match = list2.some(function(val) {
return (list[i] + val === num);
});
if (match) {
return true;
}
}
return false;
}
// Tests
console.log(
sumTwoMatch([1, 5, 3, 4, 5], 10), // true
sumTwoMatch([1, 5, 3, 4, 5], 11), // false
sumTwoMatch([1, 5, 3, 4, 5], 8), // true
sumTwoMatch([1, 5, 3, 4, 5], 3), // false
sumTwoMatch([1, 5, 3, 4, 5], 5), // true
sumTwoMatch([1, 5, 3, 4, 5], 3), // false
sumTwoMatch([1, 5, 3, 4, 5], 9), // true
sumTwoMatch([1, 5, 3, 4, 5], 2) // false
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment