Last active
August 29, 2015 14:17
-
-
Save YanivHaramati/fdb78df5abeef73a1025 to your computer and use it in GitHub Desktop.
Naive solution to subset sum problem in javascript. Given an array of numbers find any combination that adds up to the max.
This file contains 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 ArrayAddition(arr) { | |
// first get the max and remove it from the array | |
arr.sort(function(a,b) {return b-a;}); | |
var max = arr[0]; | |
var arr = arr.slice(1); | |
// get all subsets, and filter out subsets whose sum doesn't add up to max. | |
var res = subsets(arr, 2).filter(function(sub) { | |
return sum(sub) == max; | |
}); | |
// if we now have anything in the resulting array then there is some combination that adds to max. | |
return res.length > 0; | |
} | |
// sum all numbers in an array | |
function sum(arr) { | |
return arr.reduce(function(p,c) { | |
return p+c; | |
}, 0); | |
} | |
// I stole this bit of magic from stack overflow. | |
// Quite clever. | |
var subsets = function(input, size){ | |
var results = [], result, mask, total = Math.pow(2, input.length); | |
for(mask = 0; mask < total; mask++){ | |
result = []; | |
var i = input.length - 1; | |
do{ | |
if( (mask & (1 << i)) !== 0){ | |
result.push(input[i]); | |
} | |
}while(i--); | |
if( result.length >= size){ | |
results.push(result); | |
} | |
} | |
return results; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment