Last active
September 4, 2015 23:48
-
-
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
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
/** | |
* 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