Markov chain text generator: Difference between revisions

(Minor edits to my old Python implementation.)
Line 909:
she comes, to-' At this moment Five, who had been greatly interested in
</pre>
 
=={{header|Nim}}==
{{trans|Kotlin}}
import random, sequtils, strutils, tables
 
proc markov(filePath: string; keySize, outputSize: Positive): string =
 
let words = filePath.readFile().strip(false, true).splitWhitespace()
doAssert outputSize in keySize..words.len, "Output size is out of range"
 
var dict: Table[string, seq[string]]
 
for i in 0..(words.len - keySize):
let prefix = words[i..<(i+keySize)].join(" ")
let suffix = if i + keySize < words.len: words[i + keySize] else: ""
dict.mgetOrPut(prefix, @[]).add suffix
 
var output: seq[string]
var prefix = toSeq(dict.keys).sample()
output.add prefix.split(' ')
 
for n in 1..words.len:
let nextWord = dict[prefix].sample()
if nextWord.len == 0: break
output.add nextWord
if output.len >= outputSize: break
prefix = output[n..<(n + keySize)].join(" ")
 
result = output[0..<outputSize].join(" ")
 
randomize()
echo markov("alice_oz.txt", 3, 100)</lang>
 
{{out}}
<pre>soon made up her mind to wear it and carry her sunbonnet in the basket. But the Scarecrow said, We cannot fly, that is certain. Neither can we climb down into this great ditch. Therefore, if we cannot get to the door. 'Call the next witness.' And he added in an undertone to the Queen, 'Really, my dear, you will have the castle to yourself. I have been making believe. Making believe! cried Dorothy. Are you a Munchkin? asked Dorothy. No, for this pole is stuck up my back. If you will come with me I'll ask Oz to do</pre>
 
=={{header|Perl}}==
Anonymous user