Last active
November 28, 2016 01:18
-
-
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.
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
/** | |
* 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