Created
December 26, 2021 11:38
-
-
Save jamesmintram/6a64a8b1e39019b148d2fc4e5feb53e1 to your computer and use it in GitHub Desktop.
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 rover.core) | |
(def grid-size 10) | |
(def obstacles #{[2 1]}) | |
(def initial-state {:direction 0 :position [0 0]}) | |
(def move-vectors [[0 1] | |
[1 0] | |
[0 -1] | |
[-1 0]]) | |
(def direction->str {0 "N" 1 "E" 2 "S" 3 "W"}) | |
(defn rotate-right [{:keys [position direction]}] | |
{:position position | |
:direction (-> direction | |
(inc) | |
(mod 4))}) | |
(defn rotate-left [{:keys [position direction]}] | |
{:position position | |
:direction (-> direction | |
(dec) | |
(+ 4) | |
(mod 4))}) | |
(defn add-vecs [[x1 y1] [x2 y2]] | |
[(+ x1 x2) (+ y1 y2)]) | |
(defn wrap-coords [[x y]] | |
[(-> x (+ grid-size) (mod grid-size)) | |
(-> y (+ grid-size) (mod grid-size))]) | |
(defn move [{:keys [position direction]}] | |
(let [direction-vector (get move-vectors direction) | |
new-position (-> position | |
(add-vecs direction-vector) | |
(wrap-coords))] | |
{:position new-position | |
:direction direction})) | |
(defn check-collision [{:keys [position] :as new-state} old-state] | |
(if (contains? obstacles position) | |
(reduced old-state) | |
new-state)) | |
(defn apply-command [state command] | |
(case command | |
\L (rotate-left state) | |
\R (rotate-right state) | |
\M (-> (move state) | |
(check-collision state)))) | |
(defn traverse [path] | |
(reduce apply-command | |
initial-state | |
path)) | |
(defn format [{[x y] :position direction :direction}] | |
(str x ":" y ":" (direction->str direction))) | |
(comment | |
(traverse "MRMMMM") | |
(traverse "MMRMMMM") | |
(-> | |
(traverse "MRMMMM") | |
(format)) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment