Execute a Markov algorithm: Difference between revisions
Content added Content deleted
No edit summary |
(Added Kotlin) |
||
Line 2,116: | Line 2,116: | ||
000000A000000 |
000000A000000 |
||
00011H1111000</pre> |
00011H1111000</pre> |
||
=={{header|Kotlin}}== |
|||
{{trans|Java}} |
|||
<lang scala>// version 1.1.51 |
|||
import java.io.File |
|||
import java.util.regex.Pattern |
|||
/* rulesets assumed to be separated by a blank line in file */ |
|||
fun readRules(path: String): List<List<String>> { |
|||
val ls = System.lineSeparator() |
|||
return File(path).readText().split("$ls$ls").map { it.split(ls) } |
|||
} |
|||
/* tests assumed to be on consecutive lines */ |
|||
fun readTests(path: String) = File(path).readLines() |
|||
fun main(args: Array<String>) { |
|||
val rules = readRules("markov_rules.txt") |
|||
val tests = readTests("markov_tests.txt") |
|||
val pattern = Pattern.compile("^([^#]*?)\\s+->\\s+(\\.?)(.*)") |
|||
for ((i, origTest) in tests.withIndex()) { |
|||
val captures = mutableListOf<List<String>>() |
|||
for (rule in rules[i]) { |
|||
val m = pattern.matcher(rule) |
|||
if (m.find()) { |
|||
val groups = List<String>(m.groupCount()) { m.group(it + 1) } |
|||
captures.add(groups) |
|||
} |
|||
} |
|||
var test = origTest |
|||
redo@ do { |
|||
val copy = test |
|||
for (c in captures) { |
|||
test = test.replace(c[0], c[2]) |
|||
if (c[1] == ".") break |
|||
if (test != copy) continue@redo |
|||
} |
|||
break |
|||
} |
|||
while (true) |
|||
println("$origTest\n$test\n") |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<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 B of As W my Bgage from T S. |
|||
I bought a bag of apples with my money from T shop. |
|||
_1111*11111_ |
|||
11111111111111111111 |
|||
000000A000000 |
|||
00011H1111000 |
|||
</pre> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |