Execute a Markov algorithm: Difference between revisions

Content added Content deleted
(→‎{{header|REXX}}: included a CHANGESTR subroutine (function) as a link. -- ~~~~)
Line 1,051: Line 1,051:


void main() {
void main() {
string[][] rules = readText("markov_rules.txt").splitLines().
auto rules = readText("markov_rules.txt").splitLines().split("");
auto tests = readText("markov_tests.txt").splitLines();
split("");
auto regex = ctRegex!(r"^([^#]*?)\s+->\s+(\.?)(.*)");
string[] tests = readText("markov_tests.txt").splitLines();
assert(tests.length == rules.length);

// Faster to compile run-time regex
//auto regex = regex(r"^([^#]*?)\s+->\s+(\.?)(.*)");

// Compile-time regex creation
// DMD 2.059 uses about 130 MB RAM to compile this
enum regex = ctRegex!(r"^([^#]*?)\s+->\s+(\.?)(.*)");


foreach (i, test; tests) {
foreach (i, test; tests) {
auto origtest = test.dup;

string[][] capt;
string[][] capt;
foreach (line; rules[i]) {
foreach (line; rules[i]) {
auto m = line.match(regex);
auto m = line.match(regex);
if (!m.empty)
if (!m.empty) capt ~= array(m.captures)[1 .. $];
capt ~= m.captures.array()[1 .. $];
}
}
REDO: auto copy = test;

REDO:
auto copy = test;
foreach (c; capt) {
foreach (c; capt) {
test = test.replace(c[0], c[2]);
test = test.replace(c[0], c[2]);
if (c[1] == ".")
if (c[1] == ".") break;
break;
if (test != copy) goto REDO;
if (test != copy)
goto REDO;
}
}
writefln("%s\n%s\n", origtest, test);

writeln(test);
}
}
}</lang>
}</lang>
{{out}}
{{out}}
<pre>I bought a bag of apples from my brother.
<pre>I bought a B of As from T S.
I bought a bag of apples from my brother.

I bought a B of As from T S.
I bought a bag of apples from T shop.
I bought a bag of apples from T shop.

I bought a B of As W my Bgage from T S.
I bought a bag of apples with my money from T shop.
I bought a bag of apples with my money from T shop.

_1111*11111_
11111111111111111111
11111111111111111111

000000A000000
00011H1111000</pre>
00011H1111000</pre>