Execute a Markov algorithm: Difference between revisions

Content added Content deleted
(Improved D code)
Line 947: Line 947:
{{trans|Perl}}
{{trans|Perl}}
{{works with|D|2}}
{{works with|D|2}}
<lang d>import std.stdio, std.array, std.file, std.regex: match;
<lang d>import std.stdio, std.array, std.file, std.regex, std.string;

import std.string: splitlines, newline;
auto readBlocks(in string fn) {
string[][] res;
foreach (a; split(cast(string)read(fn), newline ~ newline))
res ~= a.splitlines();
return res;
}


void main() {
void main() {
// read rule sets separated by a blank line
auto rules = readFile("markov_rules.txt");
auto rules = readBlocks("markov_rules.txt");

auto tests = splitlines(cast(string)read("markov_tests.txt"));
auto tests = splitlines(cast(string)read("markov_tests.txt"));

foreach (i, rule; rules) {
foreach (i, rule; rules) {
string[][] capt;
string[][] capt;
foreach (line; rule) {
foreach (line; rule) {
auto m = match(line, r"^([^#]*?)\s+->\s+(\.?)(.*)");
auto m = match(line, r"^([^#]*?)\s+->\s+(\.?)(.*)");
if (!m.empty) capt ~= array(m.captures)[1 .. $];
if (!m.empty)
capt ~= array(m.captures)[1 .. $];
}
}

redo:
REDO:
auto copy = tests[i];
auto copy = tests[i];
foreach (c; capt) {
foreach (c; capt) {
tests[i] = replace(tests[i], c[0], c[2]);
tests[i] = replace(tests[i], c[0], c[2]);
if (c[1] == ".") break;
if (c[1] == ".")
if (tests[i] != copy) goto redo;
break;
}
if (tests[i] != copy)
writeln(tests[i]);
goto REDO;
}
}
}


writeln(tests[i]);
auto readFile(in string fn) {
string[][] res;
}
foreach (a; split(cast(string)read(fn), newline~newline))
res ~= splitlines(a);
return res;
}</lang>
}</lang>