Created
September 16, 2013 20:47
-
-
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 ] )
This file contains hidden or 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
| 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