|
| 1 | +(ns advent-of-clojure.2022.10 |
| 2 | + (:require [clojure.string :as str])) |
| 3 | + |
| 4 | +(defn parse [[op v]] |
| 5 | + (cond-> [(keyword op)] v (conj (parse-long v)))) |
| 6 | + |
| 7 | +(def input (->> "resources/2022/10.dat" slurp str/split-lines |
| 8 | + (mapv (comp parse #(str/split % #"\s"))))) |
| 9 | + |
| 10 | +(defn run-cycle [{:keys [clock register] :as state}] |
| 11 | + (-> state |
| 12 | + (update :samples conj [clock register]) |
| 13 | + (update :clock inc))) |
| 14 | + |
| 15 | +(defn final-run [{:keys [clock register] :as state}] |
| 16 | + (update state :samples conj [clock register])) |
| 17 | + |
| 18 | +(defn run [instructions] |
| 19 | + (final-run |
| 20 | + (reduce (fn [state [op value]] |
| 21 | + (case op |
| 22 | + :noop (run-cycle state) |
| 23 | + :addx (update |
| 24 | + (run-cycle (run-cycle state)) |
| 25 | + :register + value))) |
| 26 | + {:register 1 :clock 1 :samples [[0 1]]} |
| 27 | + instructions))) |
| 28 | + |
| 29 | +(defn samples [start sample-rate samples] |
| 30 | + (vals (select-keys samples (range start (count samples) sample-rate)))) |
| 31 | + |
| 32 | +(def part-one |
| 33 | + (->> input run :samples |
| 34 | + (samples 20 40) |
| 35 | + (map (partial apply *)) |
| 36 | + (reduce +))) |
| 37 | + |
| 38 | +(def empty-CRT (vec (repeat 240 \.))) |
| 39 | + |
| 40 | +(defn lit-pixel? [middle target] |
| 41 | + (contains? (set (range (dec middle) (inc (inc middle)))) target)) |
| 42 | + |
| 43 | +(defn light-pixels [CRT samples] |
| 44 | + (reduce |
| 45 | + (fn [CRT [clock register]] |
| 46 | + (let [pixel (dec clock) |
| 47 | + sprite (+ register (* 40 (int (/ pixel 40))))] |
| 48 | + (if (lit-pixel? sprite pixel) |
| 49 | + (assoc CRT pixel \#) |
| 50 | + CRT))) |
| 51 | + CRT samples)) |
| 52 | + |
| 53 | +(defn draw [CRT] |
| 54 | + (doseq [line (partition 40 CRT)] |
| 55 | + (apply println line))) |
| 56 | + |
| 57 | +(def part-two |
| 58 | + (->> input run :samples rest |
| 59 | + (light-pixels empty-CRT) |
| 60 | + draw)) |
0 commit comments