Skip to content

Instantly share code, notes, and snippets.

@little-arhat
Forked from Gonzih/README.md
Last active March 8, 2017 20:04
Show Gist options
  • Save little-arhat/dc8cc27c2eee11ace5e97aed60227212 to your computer and use it in GitHub Desktop.
Save little-arhat/dc8cc27c2eee11ace5e97aed60227212 to your computer and use it in GitHub Desktop.
markov-chain-meetup-dojo
(ns ams-cm-markov.core
(:require [clojure.java.io :as io]
[clojure.string :as str])
(:gen-class))
(defn- read-text [name]
(with-open [reader (io/reader (io/resource name))]
(doall (->> (line-seq reader)
(map #(re-seq #"\w+|\." %))
flatten
(keep not-empty)
(map str/lower-case)))))
(def text (read-text "alice.txt"))
(defn safe-inc [v]
(if v
(inc v)
1))
(defn step [acc [word next]]
(let [next-words (acc word)]
(assoc acc word (cons next next-words))))
(defn generate-chain [input]
(reduce step {} (partition 2 1 input)))
(def chain (generate-chain text))
(defn choose [wordset]
(rand-nth wordset))
(defn gen-step [[acc current-word] _]
(let [next-words (chain current-word)
chosen (choose next-words)]
[(cons current-word acc) chosen])
)
(defn generate-phrase [chain start-word min max]
(let [phrase (loop [current-word start-word
number 0
result [current-word]]
(let [next-words (chain current-word)
chosen (choose next-words)]
(cond
(and (= chosen ".") (> number max))
result
(= number max)
result
(and (= chosen ".") (= 1 (count next-words)))
(cons "." result)
(= chosen ".")
(recur current-word number result)
:else
(recur chosen
(inc number)
(cons chosen result)))))]
(str/join " " (reverse phrase))))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))

(doseq [start ["rabbit" "alice" "i" "hatter" "queen" "tea"]] (println (generate-phrase chain start 6 13)))

rabbit hole and was shrinking rapidly she picked up and the phrase project gutenberg alice heard a poor little timidly saying to donate royalties i can be done thought alice and his head brandy now you may be hatter as well say as the little pattering of the foundation at the wood queen in her so alice appeared and found herself a few minutes it might tea time for it said the great question it or longitude either way do

alice remarked the doubled up lazy thing i can listen to think very rabbit but what a wondering very well eh stupid and here lad here i can guess she felt a bit to alice chapter iii . tea said alice thought and alice the mock turtle sighed wearily . hatter looked at the dormouse very politely as well said the cool fountains queen to carry out of the project gutenberg tm collection of the last mouse who had come up to talk to turn a long time and

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment