Created
May 28, 2009 06:53
-
-
Save rapha/119145 to your computer and use it in GitHub Desktop.
find sets of positive integers which sum to another integer
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
var sums = function(num) { | |
var sets = [[num]]; | |
for (var i = 1; i <= num/2; i++) { | |
var left = sums(i); | |
var right = sums(num-i); | |
left.forEach(function(lhs) { | |
right.forEach(function(rhs) { | |
sets.push(lhs.concat(rhs).sort()); | |
}) | |
}) | |
} | |
return uniq(sets); | |
} | |
function uniq(list) { | |
var cache = {}; | |
for (var i in list) { cache[list[i].toString()] = list[i]; } | |
var result = []; | |
for (var p in cache) { result.push(cache[p]); } | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment