Execute a Markov algorithm: Difference between revisions

→‎{{header|J}}: use explicit version from Talk page
(Added Perl.)
(→‎{{header|J}}: use explicit version from Talk page)
Line 209:
 
=={{header|J}}==
{{incorrect|J|Quick & dirty solution, see [[Talk:Markov Algorithm#J|discussion of gaps]]}}
 
'''Solution''':<lang j>require'strings regex'
markovLexer =: verb define
rules rules =. LF cut TAB&=`(,:&' ')}y
rules rules =. a: -.~ (dltb@:{.~ i:&'#')&.> rules
rules =. 0 _1 {"1 '\s+->\s+' (rxmatch rxcut ])S:0 rules
(,. ] (}.&.>~ ,. ]) ('.'={.)&.>)/ |: rules
)
 
replace =: dyad define
NB. Lex a Markov program
'index patternLength replacement'=. x
markovLexer =: verb define
'head tail' =. index split y
rules =. LF cut TAB&=`(,:&' ')}y
head, replacement, patternLength }. tail
rules =. a: -.~ (dltb@:{.~ i:&'#')&.> rules
0 _1 {"1 '\s+->\s+' (rxmatch rxcut ])S:0 rules
)
 
matches =: E. i. 1:
NB. Given ruleset and target string, output
NB. result.
markovStrict =: dyad define
markov =: markovLexer@[ stringreplace^:_ ]
ruleIdx =. 0 [ rules =. markovLexer x
 
while. ruleIdx < #rules do.
NB. Same as above, but output all intermediate
'pattern replacement terminating' =. ruleIdx { rules
NB. evaluations
if. (#y) > index =. pattern matches y do.
markovDebug =: markovLexer@[ stringreplace^:a: ]</lang>
y =. (index ; (#pattern) ; replacement) replace y
if. terminating do. ruleIdx =. #rules
else. ruleIdx =. 0 end.
else.
ruleIdx =. 1 + ruleIdx
end.
end.
y
)</lang>
 
'''Example''':<lang j> m1 =. noun define
Line 241 ⟶ 254:
m1 markov 'I bought a B of As from T S.'
I bought a bag of apples from my brother.
</lang>
 
'''Discussion''': Reasons for the explicit <code>while.</code> loop and more details are available on the [[Talk:Markov Algorithm#explicit_vs_tacit|the talk page]].
m1 markovDebug 'I bought a B of As from T S.'
I bought a B of As from T S.
I bought a bag of apples from the shop.
I bought a bag of apples from my brother.</lang>
'''Discussion''': This solution implemented in 20 seconds and doesn't fully implement a Markov algorithm. More details on [[Talk:Markov Algorithm#J|the talk page]].
 
=={{header|Perl}}==
Anonymous user