Skip to content

Instantly share code, notes, and snippets.

@Yonet
Last active August 29, 2015 14:20
Show Gist options
  • Save Yonet/4f3f05f18ca479561580 to your computer and use it in GitHub Desktop.
Save Yonet/4f3f05f18ca479561580 to your computer and use it in GitHub Desktop.
//given an array of integers (x), and an integer (y), returns true if any two of the integers in x add up to y.
var addsToY = function(arr, y) {
for(var i = 0; i < arr.length; i ++) {
for (var j = i + 1; j < arr.length; j++) {
if(arr[i] + arr[j] === y) return true;
}
}
return false;
}
//Helper function to find combination arrays.
var combinations = function(arr, n) {
var result = [];
if(n == 1) {
for(var i = 0; i < arr.length; i++) {
result.push([arr[i]]);
}
return result;
} else {
for(var i = 0; i < arr.length; i++){
var currentArr = arr.slice(i+1);
var temp = combinations(currentArr, n-1);
for(var j = 0; j < temp.length; j++){
temp[j].push(arr[i]);
}
result = result.concat(temp);
}
}
return result;
}
//given the above arguments and an additional integer (z), returns true if any z of the integers in x add up to y.
var zAddsToY = function(arr, y, z) {
if(z < 0) return false;
else if(z === 1) { return arr.indexOf(y) > -1 ? true : false;}
else {
var result = [];
var arrCombinations = combinations(arr, z);
for(var i = 0; i < arrCombinations.length; i++) {
var total = 0;
for(var j = 0; j < arrCombinations[i].length; j++) {
total += arrCombinations[i][j];
}
if(total === y) return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment