Randomness in Clojure

{:deps {org.clojure/clojure {:mvn/version "1.10.1"}
        ;; complient is used for autocompletion
        ;; add your libs here (and restart the runtime to pick up changes)
        compliment/compliment {:mvn/version "0.3.9"}}}
deps.edn
Extensible Data Notation
{:hello (clojure-version)}
0.1s
Clojure

Random 101

Skill: Generate a random integer with zero minimum

;; get a random integer from 0 to 9
(rand-int 10)
0.0s
Clojure
;; a list of random integers
(repeatedly 5 #(rand-int 10))
;; same effect as above: (take 5 (repeatedly #(rand-int 10)))
;; source: https://clojuredocs.org/clojure.core/repeatedly
0.0s
Clojure

Skill: Generate a random integer with an arbitrary minimum

(defn rand-int-min-max
  "max here is inclusive"
  [min max]
  (+ min (rand-int max)))
0.0s
Clojure
;; generate 5 random numbers ranging from 1 to 20 (inclusive)
(repeatedly 5 #(rand-int-min-max 1 20))
0.0s
Clojure

Exercise: Create a "x-rolls-d-sides" function a la "D20"

(defn die-rolls-sides [rolls sides]
  (repeatedly rolls #(rand-int-min-max 1 sides)))
0.0s
Clojure
;; 3d6
(def roll-x (die-rolls-sides 3 6))
0.0s
Clojure

Skill: Create a random decimal number between 0 and 1 (exclusive).

(rand)
0.0s
Clojure
(repeatedly 10 rand)
0.0s
Clojure

Confirm that (rand) never returns 1

;; source: docs: https://clojuredocs.org/clojure.core/rand#example-542692c8c026201cdc326a0f
(some (partial <= 10) (take 100000 (repeatedly (fn [] (int (rand 10))))))
0.6s
Clojure

Exercise: Write function that return a random number of X precision between 0 and 1 (exclusive)

(defn rand-float-precision [precision]
  (/ (Math/floor (* (Math/pow 10 precision) (rand))) (Math/pow 10 precision)))
0.1s
Clojure
(repeatedly 10 #(rand-float-precision 2))
0.0s
Clojure
Runtimes (1)