JSFiddle - React, Tailwind, and code Playground
by sperske
JavaScript
const cache = new Map()
function render(result, parens = ['(',')']) {
const rendered = new Set()
for (r of result) {
let output = ''
for (d of r) {
output += parens[d]
}
rendered.add(output)
}
return rendered
}
function allBalancedStrings(n) {
if (n === 0) return ['']
const cached = cache.get(n)
if (cached) return cached
const result = []
for (let i = 0; i < n; i++) {
for (const s1 of allBalancedStrings(i)) {
for (const s2 of allBalancedStrings(n - i - 1)) {
result.push([].concat(0, ...s1, 1, ...s2))
}
}
}
cache.set(n, result)
return result
}
for (let i = 1; i < 16; i++) {
const start = Date.now()
const data = [...allBalancedStrings(i)]
const end = Date.now()
console.log(`n=${i} calculated in ${end-start}ms`)
}
console.log(4, [...render(allBalancedStrings(4), ['{', '}'])])