RosettaCodeData/Task/Balanced-brackets/D/balanced-brackets-3.d

20 lines
670 B
D
Raw Permalink Normal View History

2014-01-17 05:32:22 +00:00
import std.stdio, std.random, std.range, std.algorithm;
2013-04-10 16:57:12 -07:00
2015-02-20 00:35:01 -05:00
bool isBalanced(in string s, in char[2] pars="[]") pure nothrow @safe @nogc {
bool bal(in string t, in int nb = 0) pure nothrow @safe @nogc {
2014-01-17 05:32:22 +00:00
if (!nb && t.empty) return true;
if (t.empty || nb < 0) return false;
if (t[0] == pars[0]) return bal(t.dropOne, nb + 1);
if (t[0] == pars[1]) return bal(t.dropOne, nb - 1);
return bal(t.dropOne, nb); // Ignore char.
2013-04-10 16:57:12 -07:00
}
return bal(s);
}
void main() {
2013-06-05 21:47:54 +00:00
foreach (immutable i; 1 .. 9) {
2014-01-17 05:32:22 +00:00
immutable s = iota(i * 2).map!(_ => "[]"[uniform(0, $)]).array;
2013-06-05 21:47:54 +00:00
writeln(s.isBalanced ? " OK " : "Bad ", s);
2013-04-10 16:57:12 -07:00
}
}