Skip to content

Instantly share code, notes, and snippets.

@rauhs
Last active December 8, 2017 10:43
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 rauhs/4fe942af60f351e8ecb6c24a35855c44 to your computer and use it in GitHub Desktop.
Save rauhs/4fe942af60f351e8ecb6c24a35855c44 to your computer and use it in GitHub Desktop.
;; Utility functions:
;; Space separted number values:
(defn ssn [s] (mapv #(Long/parseLong %) (str/split s #"\s+")))
(def day5 "2\t8\t8\t5\t4\t2\t3\t1\t5\t5\t1\t2\t15\t13\t5\t14")
(def day5-ex "0 2 7 0")
(defn max-idx [xs]
(count (take-while #(not= % (apply max xs)) xs)))
(defn spread-idx
[xs idx]
(let [v (nth xs idx)]
(->> (concat (repeat idx 0) [(- v)] (repeat v 1))
(partition (count xs) (count xs) (repeat 0))
(apply mapv + xs))))
(defn solve-day-5
[xs]
(loop [seen {xs 0}, xs xs, i 1]
(let [xs* (spread-idx xs (max-idx xs))]
(if (seen xs*)
{:part1 (count seen) :part2 (- (count seen) (seen xs*))}
(recur (assoc seen xs* i) xs* (inc i))))))
#_(solve-day-5 (ssn day5))
#_(solve-day-5 (ssn day5-ex))
(let [max' (fn [xs] (apply max xs))
regs (reductions
(fn [m [reg op num _ c-reg cmp c-num]]
(let [num (Long/parseLong num)
c-num (Long/parseLong c-num)
!= not=
if-op (resolve (read-string cmp))]
(if (if-op (get m c-reg 0) c-num)
(update m reg (fnil (get {"inc" + "dec" -} op) 0) num)
m)))
{} (mapv #(str/split % #"\s+") (line-seq (io/reader "day8.txt"))))]
{:part1 (max' (vals (last regs)))
:part2 (max' (mapv max' (keep vals regs)))})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment