Skip to content

Instantly share code, notes, and snippets.

@ashishpuliyel
Created September 7, 2015 21:40
Show Gist options
  • Save ashishpuliyel/3c7eaa989f94d2376bba to your computer and use it in GitHub Desktop.
Save ashishpuliyel/3c7eaa989f94d2376bba to your computer and use it in GitHub Desktop.
/* makesPairWith returns a boolean indicating if the
* given array (inArr) contains a pair of numbers that
* add up to the target
*
* inArr - The array to be flattened
* target - The number the pairs may add up to
*/
function makesPairWith(inArr,target) {
for (var i=0; i < inArr.length; i++) {
var a = inArr[i];
// Because we don't need [b,a] if we've already looked at
// [a,b] in a previous loop we can make the inner loop
// shorter with each cycle of the outer loop.
for (var j=i+1; j < inArr.length; j++) {
var b = inArr[j];
if (a+b===target) {
return true;
}
}
}
return false;
}
/* I'm provding a function here that tests/demonstrates the makesPairWith
* function above. Returns a boolean indicating the test pass status. */
function testMakesPairWith() {
//tests is an array of objects, each with an input and an expected output
//input itself is an array which is passed to the tested function with apply
var tests = [{
input : [ [1,2,3,4,5,6,7,8,9], 12],
expected : true
}, {
input : [ [1,1,2], 2],
expected : true
}, {
input : [ [1,1,1], 3],
expected : false
}, {
input : [ [1,2,3,4,5,6], 20],
expected : false
}];
var passed = true;
tests.forEach(function(test, i) {
if (makesPairWith.apply(undefined, test.input)===test.expected) {
console.log("Test Passed:", i+1);
} else {
console.log("Test Failed:", i+1);
passed = false;
}
});
return passed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment