Balanced brackets: Difference between revisions

Content added Content deleted
m (tweak formatting of task)
Line 12: Line 12:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.algorithm, std.string,
<lang d>import std.stdio, std.algorithm, std.string, std.random;
std.range, std.random, std.conv;


auto generate(int n) {
auto generate(int n) {
return text(map!((i){ return "[]"[uniform(0,2)]; })(iota(n)));
auto r = "[]".repeat(n).dup;
randomShuffle(r);
return r;
}
}


void main() {
void main() {
foreach (i; 0 .. 14) {
foreach (i; 0 .. 9) {
auto s = generate(i);
auto s = generate(i);
writefln("%-15s is%s balanced", '"' ~ s ~ '"',
writefln("%-16s %s", s,
s.balancedParens('[', ']') ? "" : " not");
s.balancedParens('[', ']') ? "OK" : "bad");
}
}
}</lang>
}</lang>
One output:
Output:
<pre>"" is balanced
<pre> OK
"[" is not balanced
[] OK
"][" is not balanced
[[]] OK
"[]]" is not balanced
]][[][ bad
"][][" is not balanced
]][[][[] bad
"][][]" is not balanced
[[[][]][]] OK
"[[[]][" is not balanced
[[]][[][]][] OK
"[]][[[]" is not balanced
[]]]][[[[[]]][ bad
"][][][[]" is not balanced
[[[[][[]][]]]][] OK</pre>
"][]][][[]" is not balanced
"[]][[]][[]" is not balanced
"][[]]][]]][" is not balanced
"[[]][[[[]]]]" is balanced
"[[]][][]]]][[" is not balanced</pre>


=={{header|J}}==
=={{header|J}}==