/* Markov chains in Picat. http://rubyquiz.com/quiz74.html (See the description below.) This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. main => go. go => _ = random2(), % Word based text(Text), Split = split(Text," \t\n"), println(split=Split), NextWord = new_map(), foreach(I in 1..Split.length-1) Word = Split[I], NextWord.put(Word, NextWord.get(Word,[])++[Split[I+1]]) end, Words = keys(NextWord), println(words=Words), Chain = [new_random_word(Words)], println(chain=Chain), while(true) Last = Chain.last(), if NextWord.has_key(Last) then Next = new_random_word(NextWord.get(Last)) else Next = new_random_word(Words) end, Chain := Chain ++ [Next], println(chain=Chain.join(' ')) end, println(Chain), nl. new_random_word(Words) = Words[1 + random() mod Words.length]. text(Text) => Text = "This week's Ruby Quiz is about text generation. That's right, we're going to teach your computer to weave tall tales. At its most basic level, a solution might be: >> (1..30).map { ((\"a\"..\"z\").to_a + [\" \"] * 10)[rand(36)] }.join => \"fb mcr hhluesjbhtf swm eehokmi\" However, let's make our goal to get as close to English looking sentences as possible. One way you might do this is using a technique called Markov Chains. To use Markov Chains, you read some text document(s), making note of which characters commonly follow which characters or which words commonly follow other words (it works for either scale). Then, when generating text, you just select a character or word to output, based on the characters or words that came before it. The number of previous characters or words considered is called the \"order\" and you can adjust that to try and find a natural feel. For example, here is some generated text using a second order word chain derived from the Sherlock Holmes novel \"The Hound of the Baskervilles\" by Arthur Conan Doyle: The stars shone cold and bright, while a crushing weight of responsibility from my shoulders. Suddenly my thoughts with sadness. Then on the lady's face. \"What can I assist you?\" If you need text's to prime your program with, I suggest searching Project Gutenberg:".