Skip to content

Instantly share code, notes, and snippets.

@clemmy
Created November 10, 2014 18:20
Show Gist options
  • Save clemmy/e1ccd5bd4f05b143eb75 to your computer and use it in GitHub Desktop.
Save clemmy/e1ccd5bd4f05b143eb75 to your computer and use it in GitHub Desktop.
Outputting all balanced bracket expressions
outputBalancedBracket(3);
function outputBalancedBracket(n) {
for (var i=1; i<=n; ++i) {
var outputs = [];
brackets("",0,0,i,outputs);
console.log("N="+i+" "+outputs.join(','));
}
}
function brackets(output, num_open, num_close, num_pairs, outputs) {
if ((num_open == num_pairs) && (num_close == num_pairs)) {
outputs.push(output);
}
else {
if (num_open < num_pairs)
brackets(output + "[", num_open + 1, num_close, num_pairs, outputs);
if (num_close < num_open)
brackets(output + "]", num_open, num_close + 1, num_pairs, outputs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment