Skip to content

Instantly share code, notes, and snippets.

@featheredtoast
Last active December 19, 2017 20:37
Show Gist options
  • Save featheredtoast/7f5c8e0ac39ef940276f2071955b8d3b to your computer and use it in GitHub Desktop.
Save featheredtoast/7f5c8e0ac39ef940276f2071955b8d3b to your computer and use it in GitHub Desktop.
advent day 3
(defn find-adjacent-coordinate [[x y] direction]
(condp = direction
:right [(inc x) y]
:up [x (inc y)]
:left [(dec x) y]
:down [x (dec y)]))
(defn find-turn [direction]
(direction {:right :up
:up :left
:left :down
:down :right}))
(defn should-turn [position direction visited]
(nil? (visited (find-adjacent-coordinate position (find-turn direction)))))
(defn calc-next-state [count position direction visited]
(let [new-direction (if (should-turn position direction visited)
(find-turn direction)
direction)
[x y] (find-adjacent-coordinate position new-direction)]
{:count (inc count) :x x :y y :direction new-direction :visited (conj visited [x y])}))
(defn find-next-coordinates
([n {:keys [count x y direction visited] :as state}]
(if (= n count)
state
(let [next-state (calc-next-state count [x y] direction visited)]
(recur n next-state))))
([n]
(find-next-coordinates n {:count 1 :x 0 :y 0 :direction :down :visited #{[0 0]}})))
(defn calculate-distance [n]
(let [{:keys [x y]} (find-next-coordinates n)]
(+ (Math/abs x) (Math/abs y))))
(defn find-adjacent-coordinate [[x y] direction]
(condp = direction
:right [(inc x) y]
:up [x (inc y)]
:left [(dec x) y]
:down [x (dec y)]))
(defn find-turn [direction]
(direction {:right :up
:up :left
:left :down
:down :right}))
(defn find-value [[posx posy] known-values]
(->>
(for [x (range -1 2)
y (range -1 2)
:when (not (= x y 0))]
(known-values [(+ posx x) (+ posy y)]))
(keep identity)
(reduce +)))
#_(find-value [1 1] {[1 0] 2 [1 1] 1})
(defn should-turn [position direction visited]
(nil? (visited (find-adjacent-coordinate position (find-turn direction)))))
(defn calc-next-state [count position direction visited values]
(let [new-direction (if (should-turn position direction visited)
(find-turn direction)
direction)
[x y] (find-adjacent-coordinate position new-direction)
new-value (find-value [x y] values)]
{:count (inc count) :x x :y y :direction new-direction :visited (conj visited [x y]) :values (assoc values [x y] new-value)}))
(defn find-next-coordinates
([n {:keys [count x y direction visited values] :as state}]
(if (< n (values [x y]))
state
(let [next-state (calc-next-state count [x y] direction visited values)]
(recur n next-state))))
([n]
(find-next-coordinates n {:count 1 :x 0 :y 0 :direction :down :visited #{[0 0]} :values {[0 0] 1}})))
(defn calculate-distance [n]
(let [{:keys [x y]} (find-next-coordinates n)]
(+ (Math/abs x) (Math/abs y))))
(defn print-value [n]
(let [{:keys [x y values]} (find-next-coordinates n)]
(values [x y])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment