Skip to content

Instantly share code, notes, and snippets.

@chase-lambert
Last active May 17, 2023 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chase-lambert/3efe37560acb5523d358e2818fe4be67 to your computer and use it in GitHub Desktop.
Save chase-lambert/3efe37560acb5523d358e2818fe4be67 to your computer and use it in GitHub Desktop.
rendezvous with cassidoo challenge: 23.03.27
(ns roll-dice
(:require
[clojure.string :as string]
[clojure.test :refer [deftest is]))
(defn roll-dice [dice-str]
(let [roll-die (fn [die-size]
(inc (rand-int die-size)))]
(->> (string/split dice-str #"\+") ;; ["1d8" "2d10"]
(map #(string/split % #"d")) ;; (["1" "8"] ["2" "10"])
(map #(map parse-long %)) ;; ((1 8) (2 10))
(mapcat (fn [[n size]]
(repeatedly n #(roll-die size))))
(reduce + 0))))
(deftest roll-dice-test
(is (<= 4 (roll-dice "4d4") 16))
(is (<= 3 (roll-dice "3d20") 60))
(is (<= 3 (roll-dice "1d8+2d10") 28)))
(comment
(repeatedly 5 #(roll-dice "4d4")) ;; (8 11 15 14 8)
(repeatedly 5 #(roll-dice "3d20")) ;; (30 14 39 30 29)
(repeatedly 5 #(roll-dice "1d8+2d10")) ;; (13 22 25 19 19)
,)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment