Skip to content

Instantly share code, notes, and snippets.

@mullr

mullr/twelve.clj Secret

Created July 28, 2021 22:53
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 mullr/d06d7c04889dcf199d630981199e0a4a to your computer and use it in GitHub Desktop.
Save mullr/d06d7c04889dcf199d630981199e0a4a to your computer and use it in GitHub Desktop.
(require '[clojure.string :as string])
(defn parse-arg [s]
(try
(Integer/parseInt s)
(catch NumberFormatException e
(keyword s))))
(defn load-program [s]
(->> (string/split-lines s)
(map #(string/split % #" "))
(map (fn [[op & args]] (vec (cons (keyword op)
(map parse-arg args)))))
(into [])))
(def input
(load-program (slurp "day_12_input.txt")))
(def example
(load-program "cpy 41 a\ninc a\ninc a\ndec a\njnz a 2\ndec a\n"))
(def start-state
{:registers {:a 0, :b 0, :c 0, :d 0}
:pc 0})
(defn get-value [state key-or-value]
(if (keyword? key-or-value)
(get (:registers state) key-or-value)
key-or-value))
(defmulti run (fn [state i] (first i)))
(defmethod run :cpy [state [_ value reg]]
(assoc-in state [:registers reg]
(get-value state value)))
(defmethod run :inc [state [_ reg]]
(update-in state [:registers reg] inc))
(defmethod run :dec [state [_ reg]]
(update-in state [:registers reg] dec))
(defmethod run :jnz [state [_ value offset]]
(let [value (get-value state val)]
(if (= 0 value)
state
(update state :pc + offset))))
(defn run-commands [program]
;; (prn "----")
(loop [state start-state]
(if-let [instr (get program (:pc state))]
(do
;; (prn insr )
(let [state' (run state instr)
state'' (if (= (:pc state) (:pc state'))
(update state' :pc inc)
state')]
(recur state'')))
(:registers state))))
(comment
(run-commands [[:inc :a] [:dec :b]])
(run-commands [[:cpy 41 :a] [:cpy :a :b]])
(run-commands example)
(run-commands input)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment