CDE
This commit is contained in:
parent
518da4a923
commit
764da6cbbb
6144 changed files with 83610 additions and 11 deletions
10
Task/Balanced-brackets/D/balanced-brackets-1.d
Normal file
10
Task/Balanced-brackets/D/balanced-brackets-1.d
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import std.stdio, std.algorithm, std.random;
|
||||
|
||||
void main() {
|
||||
foreach (i; 1 .. 9) {
|
||||
string s;
|
||||
foreach (_; 0 .. i * 2)
|
||||
s ~= "[]"[uniform(0, 2)];
|
||||
writeln(s.balancedParens('[', ']') ? " OK: " : "bad: ", s);
|
||||
}
|
||||
}
|
||||
20
Task/Balanced-brackets/D/balanced-brackets-2.d
Normal file
20
Task/Balanced-brackets/D/balanced-brackets-2.d
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import std.stdio, std.random;
|
||||
|
||||
void main() {
|
||||
NEXT_STR:
|
||||
foreach (j; 1 .. 9) {
|
||||
string s;
|
||||
foreach (_; 0 .. j * 2)
|
||||
s ~= "[]"[uniform(0, 2)];
|
||||
|
||||
int balance;
|
||||
foreach (i, c; s) {
|
||||
balance += (c == '[') ? 1 : ((c == ']') ? -1 : 0);
|
||||
if (balance < 0 || balance >= s.length - i) {
|
||||
writefln("BAD: %s (%s)", s, balance < 0 ? "-" : "+");
|
||||
continue NEXT_STR;
|
||||
}
|
||||
}
|
||||
writefln(" OK: %s (=)", s);
|
||||
}
|
||||
}
|
||||
20
Task/Balanced-brackets/D/balanced-brackets-3.d
Normal file
20
Task/Balanced-brackets/D/balanced-brackets-3.d
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import std.stdio, std.random, std.conv, std.range, std.algorithm;
|
||||
|
||||
bool isBalanced(in char[] s) pure nothrow {
|
||||
static bool bal(in char[] s, in int nb=0) pure nothrow {
|
||||
if (nb == 0 && s.empty) return true;
|
||||
if (s.empty || nb < 0) return false;
|
||||
if (s[0] == '[') return bal(s[1 .. $], nb + 1);
|
||||
if (s[0] == ']') return bal(s[1 .. $], nb - 1);
|
||||
return bal(s[1 .. $], nb); // ignore char
|
||||
}
|
||||
return bal(s);
|
||||
}
|
||||
|
||||
void main() {
|
||||
foreach (i; 1 .. 9) {
|
||||
auto sr = iota(i * 2).map!(_ => ['[',']'][uniform(0, 2)])();
|
||||
auto s = sr.array();
|
||||
writefln("%5s: %s", s.isBalanced().text(), s);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue