Skip to content

Instantly share code, notes, and snippets.

@erwinv
Last active January 27, 2022 14:36
Show Gist options
  • Save erwinv/222cfb0cf53f1be18c46785ba945e385 to your computer and use it in GitHub Desktop.
Save erwinv/222cfb0cf53f1be18c46785ba945e385 to your computer and use it in GitHub Desktop.
function* parenthesesPermutations_(prefix, nOpen, nClose, score) {
if (score < 0) {
return;
}
if (nOpen === 0 && nClose === 0) {
if (score === 0) {
yield prefix;
}
return;
}
if (nOpen > 0) {
yield* parenthesesPermutations_(prefix + '(', nOpen - 1, nClose, score + 1);
}
if (nClose > 0) {
yield* parenthesesPermutations_(prefix + ')', nOpen, nClose - 1, score - 1);
}
}
function* parenthesesPermutations(n) {
return yield* parenthesesPermutations_('', n, n, 0)
}
async function main() {
const batchSize = 100;
let batch = [];
for (const p of parenthesesPermutations(12)) {
if (batch.length < batchSize) {
batch.push(p);
} else {
console.log(batch.join('\n'));
batch = [];
}
}
if (batch.length > 0) {
console.log(batch.join('\n'));
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment