Last active
October 20, 2017 19:17
-
-
Save Spuffynism/c2ec30c94c75a26ab70e76f4706f7c01 to your computer and use it in GitHub Desktop.
Get if array item has complement
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
var hasComplement = function (array, sum) { | |
if (sum < 0) | |
throw "sum must be bigger than 0"; | |
var complements = []; | |
for (var i = 0, complement; i < array.length; i++, complement = sum - array[i]) { | |
if (array.indexOf(complement) != -1) // if (complement.indexOf(array[i]) != -1) | |
return true; | |
else | |
complements.push(complement); | |
} | |
return false; | |
}; | |
var notFoundable = [1,9,3,2], | |
foundable = [1,4,2,4], | |
charles = [4,3,5,1]; | |
hasComplement(notFoundable, 8); | |
hasComplement(foundable, 8); | |
hasComplement(charles, 8); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment