Created
March 7, 2016 23:08
-
-
Save playwellsteve/e21749b24d542fe1d7ce to your computer and use it in GitHub Desktop.
Sum of combinations
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
// 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