Skip to content

Instantly share code, notes, and snippets.

@the-frey
Last active January 25, 2019 14:21
Show Gist options
  • Save the-frey/f4428dd57a2ec316153d3a4c804ac928 to your computer and use it in GitHub Desktop.
Save the-frey/f4428dd57a2ec316153d3a4c804ac928 to your computer and use it in GitHub Desktop.
(def default-file-location "./data/wordlist.csv")
(defn load-wordlist-file [path-with-extension]
(with-open [reader (io/reader path-with-extension)]
(doall
(csv/read-csv reader))))
(defn wordlist-numbered-mapping [file-location]
(reduce (fn [acc i]
(assoc acc (Integer/parseInt (first i)) (second i)))
{}
(load-wordlist-file file-location)))
;; my former colleague suggests this - requires more explaining, but it's nice and terse
;; decide which suits the audience and your temperament :)
;; note it returns strings
(defn build-wordmap [f]
(let [words (load-wordlist-file f)]
(zipmap (map first words)
(map second words))))
;; instructor's notes - get the students to implement this guy.
(defn dice-roll->word [hash-map dice-roll]
(get hash-map
dice-roll))
;; then, something like the below
;; there are a bunch of ways of doing this
;; but here's a quick implementation
(defn roll-dice []
(-> (rand-int 5)
inc))
(defn roll-multiple-dice [num-dice]
(->> (repeatedly roll-dice)
(take num-dice)))
(defn multiple-dice->string [dice-coll]
(->> dice-coll
(map str)
clojure.string/join))
(defn generate-pass-phrase []
(let [word-mapping (wordlist-numbered-mapping default-file-location)
six-sets-of-five-rolls (take 6
(repeatedly (partial roll-multiple-dice
5)))]
(->> six-sets-of-five-rolls
(map multiple-dice->string)
(map #(Integer/parseInt %))
(map #(dice-roll->word word-mapping
%)))))
;; After the above, or something like them have been implemented,
;; there will be lots of refactorings possible. For example -
;; removing intermediate collections, memoizing loads, eliminating i/o etc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment