Skip to content

Instantly share code, notes, and snippets.

@jukworks
Last active December 24, 2015 03:59
Show Gist options
  • Save jukworks/6741114 to your computer and use it in GitHub Desktop.
Save jukworks/6741114 to your computer and use it in GitHub Desktop.
A simulation code for the "A knight's random walk" problem at http://goo.gl/4aXgH
;; possible moves of a knight
(def possible-moves [[2 1] [2 -1] [1 2] [1 -2] [-1 -2] [-1 2] [-2 -1] [-2 1]])
;; he doesn't want to fall down
(defn valid-pos [xs]
(let [[x y] xs]
(and (<= 0 x 7) (<= 0 y 7))))
;; he makes one random move
(defn one-step [xy]
(let [[x y] xy]
(->> possible-moves
(map #(map + [x y] %))
(filter valid-pos)
rand-nth)))
;; he goes here and there until he comes home
(defn random-walk [init-pos]
(let [first-step (one-step init-pos)]
(loop [[x y] first-step
ct 1]
(if (= x y 0)
ct
(recur (one-step [x y]) (inc ct))))))
;; infinite tries
(defn random-walks []
(cons (random-walk [0 0]) (lazy-seq (random-walks))))
;; we set the limit for him
(defn get-average [times]
(-> (reduce + (take times (random-walks)))
(/ (double times))))
;; (get-average 100000)
;; 167.82348
;; The mathematical answer is 168
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment