Skip to content

Instantly share code, notes, and snippets.

@panda01
Last active August 29, 2015 14:13
Show Gist options
  • Save panda01/d183adb0d37ce4a8feb4 to your computer and use it in GitHub Desktop.
Save panda01/d183adb0d37ce4a8feb4 to your computer and use it in GitHub Desktop.
Just some interesting code, for
(function() {
var sumOfAnyTwo = function(sum, operandsArr) {
var oper1 = null,
oper2 = null;
for(var i = 0; i < operandsArr.length; i++) {
for(var j = 0; j < operandsArr.length; j++) {
if(j !== i) {
if(operandsArr[i] + operandsArr[j] === sum) {
return true;
}
}
}
}
return false;
},
// Better version
sumOfAnyN = function(sum, n, operandsArr, prevValue) {
var editedArr = null;
if(typeof prevValue === 'undefined') {
prevValue = 0;
}
n--;
for(var i = 0; i < operandsArr.length; i++) {
if(n > 0) {
// copy the array, and remove this item
if(sumOfAnyN(sum, n, editedArr = operandsArr.slice(), prevValue + editedArr.splice(i, 1)[0])) {
return true;
}
} else if( prevValue + operandsArr[i] === sum ) {
return true;
}
}
return false;
};
console.log(sumOfAnyN(20, 2, [8, 2, 29, 7, 10, 11, 1, 17, 14, 13]));
console.log(sumOfAnyN(27, 4, [2, 29, 7, 11, 1, 13]));
console.log(sumOfAnyN(33, 3, [8, 2, 29, 7, 10, 19, 21, 11, 1, 17, 14, 13]));
console.log(sumOfAnyN(112, 2, [8, 2, 29, 7, 17, 14, 13, 55, 60, 43, 90, 1, 23, 89, 11]));
console.log(sumOfAnyN(89, 4, [29, 7, 10, 11, 1, 17, 14, 13]));
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment