Skip to content

Instantly share code, notes, and snippets.

@seriousManual
Last active August 29, 2015 14:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seriousManual/ac5e38658caf60a4ad94 to your computer and use it in GitHub Desktop.
Save seriousManual/ac5e38658caf60a4ad94 to your computer and use it in GitHub Desktop.
Lazy creation of all combinations of a array of arbitrary length

An array with the length of 16 has 16! possible combinations (2.092279e+13), if one would like to operate on this set of combinations it is neccessary to generate all of them upfront. This alternative approach using ECMA6 generators creates these combinations on demand thus being extremely memory efficient.

var iterator = combinations([1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13]);
var handle = setInterval(function() {
var next = iterator.next();
if (next.done) {
clearInterval(handle);
} else {
console.log(next.value);
}
}, 1000);
function* combinations(input) {
if (input.length == 1) {
yield input;
return;
}
var result = [];
for(var i = 0; i < input.length; i++) {
var subResult = [];
var tail = input.concat([]);
var head = input[i];
tail.splice(i, 1);
for (var combination of combinations(tail)) {
yield [head].concat(combination);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment