Created
December 10, 2022 07:08
-
-
Save quephird/f32235c9b14f4073bac20a3289fed60d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require ['clojure.string :as 'str]) | |
(def cpu (atom {:x 1 :cycles 0})) | |
(def log (atom [1])) | |
(def crt (atom [])) | |
(defn draw-pixel [] | |
(let [x (get-in @cpu [:x]) | |
cycle (get-in @cpu [:cycles])] | |
(if (and (>= (rem cycle 40) (dec x)) | |
(<= (rem cycle 40) (inc x))) | |
(swap! crt conj "#") | |
(swap! crt conj ".")))) | |
(defn tick [] | |
(draw-pixel) | |
(swap! cpu update-in [:cycles] inc) | |
(swap! log conj (get-in @cpu [:x]))) | |
(defn noop [] | |
(tick)) | |
(defn addx [n] | |
(tick) | |
(tick) | |
(swap! cpu update-in [:x] + n)) | |
(defn parse-line [line] | |
(let [[instruction arg] (str/split line #" ")] | |
(if (nil? arg) | |
[instruction] | |
[instruction (Integer/parseInt arg)]))) | |
(defn parse-input [filename] | |
(->> filename | |
slurp | |
str/split-lines | |
(map parse-line))) | |
(defn execute-statement! [[instruction arg]] | |
(case instruction | |
"noop" | |
(noop) | |
"addx" | |
(addx arg) | |
:else | |
nil)) | |
(defn execute-program! [filename] | |
(let [program (parse-input filename)] | |
(doseq [statement program] | |
(execute-statement! statement)))) | |
(defn reset-all! [] | |
(reset! cpu {:x 1 :cycles 0}) | |
(reset! log [1]) | |
(reset! crt [])) | |
(defn solution-part-one [] | |
(->> [20 60 100 140 180 220] | |
(map (fn [n] (* n (get @log n)))) | |
(apply +))) | |
(defn solution-part-two [] | |
(let [display-lines (->> @crt | |
(partition 40) | |
(map #(apply str %)))] | |
(doseq [line display-lines] | |
(println line)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment