Jump to content

Execute a Markov algorithm: Difference between revisions

Added groovy version
(Added groovy version)
Line 405:
 
 
_
 
;---------------------------------------------------------------------------
Button1: ; http://rosettacode.org/wiki/Execute_a_Markov_algorithm#Ruleset_1
Line 1,208:
no failures
</pre>
 
=={{header|Groovy}}==
<lang groovy>def markovInterpreterFor = { rules ->
def ruleMap = [:]
rules.eachLine { line ->
(line =~ /\s*(.+)\s->\s([.]?)(.+)\s*/).each { text, key, terminating, value ->
if (key.startsWith('#')) { return }
ruleMap[key] = [text: value, terminating: terminating]
}
}
[interpret: { text ->
def originalText = ''
while (originalText != text) {
originalText = text
for (Map.Entry e : ruleMap.entrySet()) {
if (text.indexOf(e.key) >= 0) {
text = text.replace(e.key, e.value.text)
if (e.value.terminating) {
return text
}
break
}
}
}
text
}]
}</lang>
The test code is below (with the markov rulesets 2..5 elided):
<lang groovy>def verify = { ruleset ->
[withInput: { text ->
[hasOutput: { expected ->
def result = ruleset.interpret(text)
println "Input: '$text' has output: '$result'"
assert expected == result
}]
}]
}
 
def ruleset1 = markovInterpreterFor("""
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule""")
println ruleset1.interpret('I bought a B of As from T S.')
verify ruleset1 withInput 'I bought a bag of apples from T shop.' hasOutput 'I bought a bag of apples from my brother.'
 
def ruleset2 = markovInterpreterFor("""...""")
verify ruleset2 withInput 'I bought a B of As from T S.' hasOutput 'I bought a bag of apples from T shop.'
 
def ruleset3 = markovInterpreterFor("""...""")
verify ruleset3 withInput 'I bought a B of As W my Bgage from T S.' hasOutput 'I bought a bag of apples with my money from T shop.'
 
def ruleset4 = markovInterpreterFor("""...""")
verify ruleset4 withInput '_1111*11111_' hasOutput '11111111111111111111'
 
def ruleset5 = markovInterpreterFor("""...""")
verify ruleset5 withInput '000000A000000' hasOutput '00011H1111000'</lang>
{{out}}
<pre>
I bought a bag of apples from my brother.
Input: 'I bought a bag of apples from T shop.' has output: 'I bought a bag of apples from my brother.'
Input: 'I bought a B of As from T S.' has output: 'I bought a bag of apples from T shop.'
Input: 'I bought a B of As W my Bgage from T S.' has output: 'I bought a bag of apples with my money from T shop.'
Input: '_1111*11111_' has output: '11111111111111111111'
Input: '000000A000000' has output: '00011H1111000'
</pre>
 
 
 
=={{header|Haskell}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.