Skip to content

Instantly share code, notes, and snippets.

@amoilanen
Created March 13, 2015 16:49
Show Gist options
  • Save amoilanen/bb5a7456254e9d8c7fd3 to your computer and use it in GitHub Desktop.
Save amoilanen/bb5a7456254e9d8c7fd3 to your computer and use it in GitHub Desktop.
Generates sequences of a given length from specified elements, i.e. all binary numbers of fixed length
function generate(elements, len) {
if (len == 1) {
return elements.map(function(element) {
return [element];
});
}
var generated = [];
var subsequences = generate(elements, len - 1);
subsequences.forEach(function(subsequence) {
elements.forEach(function(element) {
var copy = subsequence.slice();
copy.push(element);
generated.push(copy);
});
});
return generated;
}
console.log(generate([0, 1], 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment