Skip to content

Instantly share code, notes, and snippets.

@hackingbeauty
Created September 16, 2013 20:47
Show Gist options
  • Select an option

  • Save hackingbeauty/6586395 to your computer and use it in GitHub Desktop.

Select an option

Save hackingbeauty/6586395 to your computer and use it in GitHub Desktop.
Get the count of all subsets in array [1,2,3,4,6], that when summed, equal any element in the array. Input: [1,2,3,4,6] Output: 4 (The subsets are: [ 1, 2 ], [ 1, 3 ], [ 2, 4 ], [ 1, 2, 3 ] )
function findSubsets(arr){
var subsets = [],
permutations = getPermutations(arr,2);
console.log(findInArr(arr, permutations));
return findInArr(arr, permutations).length;
}
function findInArr(arr, permutations){
var returnArr = [], sum;
for(var i = 0; i<permutations.length; i++){ // iterate through each permutation
sum = 0; //initialize
for(var j = 0; j < permutations[i].length; j++){ // sum each value in each permutation
sum = sum + permutations[i][j];
}
if(arr.indexOf(sum) !== -1){ // if the sum exists in the given array, that's good
returnArr.push(permutations[i]);
}
}
return returnArr;
}
function getPermutations(a, min) {
var fn = function(n, src, got, all) {
if (n == 0) {
if (got.length > 0) {
all[all.length] = got;
}
return;
}
for (var j = 0; j < src.length; j++) {
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
}
return;
}
var all = [];
for (var i = min; i < a.length; i++) {
fn(i, a, [], all);
}
all.push(a);
return all;
}
console.log(findSubsets([1,2,3,4,6]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment