Skip to content

Instantly share code, notes, and snippets.

@defHLT
Last active December 10, 2016 17:10
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 defHLT/d778287fd521c266e190163c595c0e13 to your computer and use it in GitHub Desktop.
Save defHLT/d778287fd521c266e190163c595c0e13 to your computer and use it in GitHub Desktop.
Advent of Code 2016 -- day 1
(ns advent-of-code.day-1)
(def data
(let [xf (map (fn [x] [(if (= (first x) \R) 1 -1)
(Integer/parseInt (apply str (rest x)))]))]
(as-> (slurp "resources/aoc-d1-input") $
(clojure.string/split $ #"[, \n]+")
(into [] xf $))))
(def locations (atom #{}))
(def first-return (atom nil))
(defn to-xy
[{:keys [n e w s]}]
[(- n s) (- e w)])
(defn manhattan-dist
[[x y]]
(+ (Math/abs x)
(Math/abs y)))
(defn check-loc
[new-loc]
(if (nil? @first-return)
(if (@locations new-loc)
(reset! first-return new-loc)
(swap! locations conj new-loc))))
(defn upd-dirs
[{:keys [stats dirs current] :as all} [d amount]]
(let [delta (cond (pos? amount) 1
(neg? amount) -1
:else 0)
step-fn (fn [x] (+ x delta))
next-i (mod (+ current d) 4)
next-key (get dirs next-i)
stats (reduce (fn [acc _]
(let [acc (update-in acc [next-key] step-fn)]
(check-loc (to-xy acc))
acc))
stats
(range amount))]
(assoc all :current next-i :stats stats)))
(defn -main
[]
(let [acc {:stats {:n 0 :e 0 :s 0 :w 0}
:dirs [:n :e :s :w]
:current 0}]
(as-> data $
(reduce (fn [acc input] (upd-dirs acc input))
acc
$)
(:stats $)
(println "Total distance:" (manhattan-dist (to-xy $)))
(println "Distance to first return point:"
(manhattan-dist @first-return)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment