Created
August 26, 2015 15:57
-
-
Save gyulalaszlo/d75c6f2162f61dd712df to your computer and use it in GitHub Desktop.
Loaded dice simulation in clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns clj-loaded-dice.core) | |
(defn make-loaded-dice | |
"Create the data structure for the loaded dice." | |
[& probabilities] | |
(let [total-probability (apply + probabilities)] | |
(->> | |
;; normalize the probabilities to sum up to 1 | |
(map #(/ % total-probability) probabilities) | |
;; Get the top of the probability for the given side | |
(reduce (fn [memo p] | |
(conj memo (+ p (if (seq memo) (last memo) 0)))) | |
[]) | |
;; Add the sides of the dice | |
(map-indexed (fn [i e] [(+ 1 i) e]))))) | |
(defn roll-loaded-dice | |
"Rolls a single loaded dice." | |
[dice] | |
(let [roll (rand)] | |
;; Since the output of (rand) is 1.0 exclusive, we | |
;; can safely use the > operator | |
(some (fn [[side sum]] (when (> sum roll) side)) dice))) | |
(defn roll-multiple-dices | |
"Rolls dice-count loaded dices throw count times and sums up the | |
results of each roll." | |
[throw-count dice-count dice] | |
(map | |
(fn [_] | |
(apply + (map | |
(fn [_] (roll-loaded-dice dice)) | |
(range dice-count)))) | |
(range throw-count))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(roll-multiple-dices 100 4 (make-loaded-dice 0.1 0.4 0.7)) | |
=> (7 8 11 10 10 12 9 10 9 10 8 9 10 10 10 11 9 12 12 11 10 12 10 11 9 11 10 9 10 9 12 10 10 10 11 9 9 12 7 8 10 11 12 11 11 11 11 12 8 12 10 10 9 11 10 11 12 10 10 10 9 9 10 10 11 11 9 8 8 9 9 9 10 7 8 8 10 11 11 11 12 10 12 9 10 10 10 10 12 8 10 9 11 11 11 10 11 8 7 9) | |
(roll-multiple-dices 100 4 (make-loaded-dice 0.1 0.1 0.1)) | |
=> (7 10 7 9 10 7 5 9 6 9 7 7 8 9 10 9 10 12 8 9 7 7 10 10 9 8 8 9 8 11 8 7 10 6 4 10 8 11 7 6 5 9 8 9 7 8 9 6 7 10 10 7 9 8 9 6 6 8 9 9 10 11 12 9 12 10 10 6 8 8 7 6 7 8 7 9 7 5 9 9 7 7 10 10 7 8 8 7 10 9 10 6 9 8 8 6 12 6 7 8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment