Anonymous user
Execute a Markov algorithm: Difference between revisions
→{{header|J}}: use explicit version from Talk page
Underscore (talk | contribs) (Added Perl.) |
(→{{header|J}}: use explicit version from Talk page) |
||
Line 209:
=={{header|J}}==
'''Solution''':<lang j>require'strings regex'
markovLexer =: verb define▼
(,. ] (}.&.>~ ,. ]) ('.'={.)&.>)/ |: rules
)
replace =: dyad define
'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:
markovStrict =: dyad define
ruleIdx =. 0 [ rules =. markovLexer x
while. ruleIdx < #rules do.
'pattern replacement terminating' =. ruleIdx { rules
if. (#y) > index =. pattern matches y do.
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]].
=={{header|Perl}}==
|