Skip to content

Instantly share code, notes, and snippets.

@playwellsteve
Created March 7, 2016 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save playwellsteve/e21749b24d542fe1d7ce to your computer and use it in GitHub Desktop.
Save playwellsteve/e21749b24d542fe1d7ce to your computer and use it in GitHub Desktop.
Sum of combinations
// requires an array sorted in ascending order
var possibleCombinationSum = function(arr, n) {
// easiest case: n is in the array somewhere
if (arr.indexOf(n) >= 0) { return true; }
// if the smallest element is > n, no solution, so finish
if (arr[0] > n) { return false; }
// get rid of any elements larger than n, recursively
if (arr[arr.length - 1] > n) {
arr.pop();
return possibleCombinationSum(arr, n);
}
var listSize = arr.length, combinationsCount = (1 << listSize)
for (var i = 1; i < combinationsCount ; i++ ) {
var combinationSum = 0;
for (var j=0 ; j < listSize ; j++) {
if (i & (1 << j)) { combinationSum += arr[j]; }
}
if (n === combinationSum) { return true; }
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment