Jump to content

Balanced brackets: Difference between revisions

m (tweak formatting of task)
Line 12:
 
=={{header|D}}==
<lang d>import std.stdio, std.algorithm, std.string, std.random;
std.range, std.random, std.conv;
 
auto generate(int n) {
returnauto text(map!((i){r return= "[]"[uniform(0,2)]; })(iota.repeat(n))).dup;
randomShuffle(r);
return r;
}
 
void main() {
foreach (i; 0 .. 149) {
auto s = generate(i);
writefln("%-15s16s is%s balanced", '"' ~ s ~ '"',
s.balancedParens('[', ']') ? "OK" : " notbad");
}
}</lang>
One output:
Output:
<pre>"" is balanced OK
"["] is not balancedOK
"][" []] is not balancedOK
"[]]" [[][ is not balancedbad
"]][[][" [] is not balancedbad
"[[[][]][]" ] is not balancedOK
"[[]][[][]][" ] is not balancedOK
"[]]]][[[[[]" ]][ is not balancedbad
"[[[[][[]][][]]][]" is not balancedOK</pre>
"][]][][[]" is not balanced
"[]][[]][[]" is not balanced
"][[]]][]]][" is not balanced
"[[]][[[[]]]]" is balanced
"[[]][][]]]][[" is not balanced</pre>
 
=={{header|J}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.