Skip to content

Instantly share code, notes, and snippets.

@specificityy
Last active September 4, 2015 23:48
Show Gist options
  • Save specificityy/1f38cf73eff7ed83bd0d to your computer and use it in GitHub Desktop.
Save specificityy/1f38cf73eff7ed83bd0d to your computer and use it in GitHub Desktop.
Function that given a specific number (let's call it `n`) and an array of numbers (let's call it `numbers`) returns a Boolean, indicating if there is a pair of numbers in `numbers` that together add up to `n`. e.g.: n = 12, numbers = [1,2,3,4,5,6,7,8,9] -> true (because 5 + 7 == 12) e.g.2.: n = 20, numbers = [1,2,3,4,5,6] -> false
/**
* Checks if there's a pair of numbers in the array which add up to n.
*
* @param {Array} numbers The array to searched on.
* @param {number} n The number to be compared.
* @returns {boolean} Returns true if no matches are found.
*/
function isSumInArray(numbers, n) {
if (isNaN(n) || !numbers || !Array.isArray(numbers)) {
return undefined;
}
var outerIndex = -1,
flag = false,
length = numbers.length;
while (++outerIndex < length && !flag) {
var innerIndex = outerIndex,
value = Number(numbers[outerIndex]);
while(!isNaN(value) && ++innerIndex < length && !flag) {
flag = (value + Number(numbers[innerIndex])) == n;
}
}
return flag;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment