Skip to content

Instantly share code, notes, and snippets.

@abp
Created December 18, 2011 22:47
Show Gist options
  • Save abp/1494716 to your computer and use it in GitHub Desktop.
Save abp/1494716 to your computer and use it in GitHub Desktop.
(ns mars-rovers.core)
(def dirs [:N :E :S :W])
(def move-dir {:N [0, 1] :E [1, 0] :S [0, -1] :W [-1, 0]})
(defn turn [dir dirs]
(second
(drop-while
(complement #(= % dir))
(cycle dirs))))
(defn turn-left [dir]
(turn dir (reverse dirs)))
(defn turn-right [dir]
(turn dir dirs))
(defn move [x y dir]
(conj
(vec
(map + [x y]
(move-dir dir)))
dir))
(defn check-position [[[x y] [max-x max-y] :as all]]
(if (and (<= 0 x max-x) (<= 0 y max-y))
all
(throw (java.lang.IllegalArgumentException.
(str "Rover fall of the plateau at: " x \space y)))))
(defn rover-action [[[x y dir] [max-x max-y]] action]
(check-position
[(cond
(= action \L) [x y (turn-left dir)]
(= action \R) [x y (turn-right dir)]
(= action \M) (move x y dir))
[max-x
max-y]]))
(defn deploy-rover [start bounds path]
(reduce rover-action [start bounds] path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment