Skip to content

Instantly share code, notes, and snippets.

@keksipurkki
Created March 12, 2022 06:08
Show Gist options
  • Save keksipurkki/dda05fa3a3452f8427cd7405700557e4 to your computer and use it in GitHub Desktop.
Save keksipurkki/dda05fa3a3452f8427cd7405700557e4 to your computer and use it in GitHub Desktop.
All binary srings of given length
#!/usr/bin/env node
function memoize(fn) {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
cache[key] = cache[key] || fn(...args);
return cache[key];
};
}
let binaryStrings = memoize(function (level) {
if (level < 0) {
throw new Error("Expected a nonnegative integer");
}
const bits = ["0", "1"];
const result = [];
if (level === 0) {
return result;
}
if (level === 1) {
return bits;
}
for (const string of binaryStrings(level - 1)) {
for (const bit of bits) {
result.push(bit + string);
}
}
return result;
});
function main(level = 0) {
console.log(`-- Binary strings of length ${level}`);
for (const string of binaryStrings(Number(level))) {
console.log(string);
}
}
main(...process.argv.slice(2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment