Skip to content

Instantly share code, notes, and snippets.

@wilson428
Created June 13, 2018 20:46
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 wilson428/f69921c50cf2b3bf89b7bab90bacbee9 to your computer and use it in GitHub Desktop.
Save wilson428/f69921c50cf2b3bf89b7bab90bacbee9 to your computer and use it in GitHub Desktop.
Generate every sequence of K integers adding to N in any order, allowing for repeats
function generateSequences(n, k) {
var sequences = [];
function getSequences(n, k, sequence) {
// calculate the highest possible value of a number, such that it leaves at least enough left over to fill the rest with 1s
var upper = n - k + 1;
for (var c = 1; c <= upper; c += 1) {
var sub_sequence = sequence.slice(0);
sub_sequence.push(c);
// how many slots remain and how much remaining value do we have?
var remaining_slots = k - 1;
var remaining_value = n - c;
if (remaining_slots == 1) {
sub_sequence.push(remaining_value);
sequences.push(sub_sequence.slice(0));
} else {
getSequences(n - c, k - 1, sub_sequence);
}
}
}
getSequences(n, k, []);
return sequences;
}
p = generateSequences(33, 4);
console.log(p);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment