Skip to content

Instantly share code, notes, and snippets.

@devirr
Last active October 28, 2019 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devirr/4b38992d858f98d5617998ac012928c6 to your computer and use it in GitHub Desktop.
Save devirr/4b38992d858f98d5617998ac012928c6 to your computer and use it in GitHub Desktop.
Journeys
(def data (clojure.string/split (slurp "./resources/journeys.data") #"\n\n"))
(defn parse [val]
(let [[_ n1 n2 c1 s n3 n4 c2] (re-matches #"(\d+) (\d+) (\w)\n(\w+)\n(\d+) (\d+) (\w)" val)
[x1 y1 x2 y2] (map int [n1 n2 n3 n4])
[d1 d2] (map keyword [c1 c2])
ops (map keyword (clojure.string/split s #""))]
{:start [x1 y1 d1] :ops ops :end [x2 y2 d2]}))
(defn move
[x y d]
(condp = d
:N [x (inc y) d]
:E [(inc x) y d]
:S [x (dec y) d]
:W [(dec x) y d]))
(def lookup
{:clockwise
{:N :E
:E :S
:S :W
:W :N}
:counterclockwise
{:N :W
:W :S
:S :E
:E :N}})
(defn calc
[[x y d] op]
(condp = op
:R [x y (get-in lookup [:clockwise d])]
:L [x y (get-in lookup [:counterclockwise d])]
:F (move x y d)))
(defn calc-all
[input]
(let [{:keys [start ops end]} input]
(loop [s start q ops e end res [start]]
(if (empty? q)
(assoc input :journey res :eq? (= e (last res)))
(let [nxt (calc s (first q))]
(recur nxt (rest q) e (conj res nxt)))))))
(defn runner [data] (->> data (map parse) (map calc-all)))
;; output
;; > (runner data)
;; ({:start [1 1 :E], :ops (:R :F :R :F :R :F :R :F), :end [1 1 :E],
;; :journey [[1 1 :E] [1 1 :S] [1 0 :S] [1 0 :W] [0 0 :W] [0 0 :N] [0 1 :N] [0 1 :E] [1 1 :E]],
;; :eq? true}
;; {:start [3 2 :N], :ops (:F :R :R :F :L :L :F :F :R :R :F :L :L), :end [3 3 :N],
;; :journey [[3 2 :N] [3 3 :N] [3 3 :E] [3 3 :S] [3 2 :S] [3 2 :E] [3 2 :N] [3 3 :N] [3 4 :N] [3 4 :E] [3 4 :S] [3 3 :S] [3 3 :E] [3 3 :N]],
;; :eq? true}
;; {:start [0 3 :W], :ops (:L :L :F :F :F :L :F :L :F :L), :end [2 4 :S],
;; :journey [[0 3 :W] [0 3 :S] [0 3 :E] [1 3 :E] [2 3 :E] [3 3 :E] [3 3 :N] [3 4 :N] [3 4 :W] [2 4 :W] [2 4 :S]],
;; :eq? true})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment