Skip to content

Instantly share code, notes, and snippets.

@rapha
Created May 28, 2009 06:53
Show Gist options
  • Save rapha/119145 to your computer and use it in GitHub Desktop.
Save rapha/119145 to your computer and use it in GitHub Desktop.
find sets of positive integers which sum to another integer
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