Skip to content

Instantly share code, notes, and snippets.

@APB9785
Created July 28, 2021 21:26
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 APB9785/e24af137b8207ff7fe73376ae5783cdf to your computer and use it in GitHub Desktop.
Save APB9785/e24af137b8207ff7fe73376ae5783cdf to your computer and use it in GitHub Desktop.
StackOverflowError
(require '[clojure.string :as string])
(def pattern #"(\w+) (\w+) ?([\w-]+)?")
(def input
(->> (slurp "day_12_input.txt")
(string/split-lines)
(map #(rest (re-find pattern %)))))
(def example
(->> "cpy 41 a\ninc a\ninc a\ndec a\njnz a 2\ndec a\n"
(string/split-lines)
(map #(rest (re-find pattern %)))))
(defn get-value [key-or-value state]
(if (contains? #{"a" "b" "c" "d"} key-or-value)
(get state key-or-value)
(Integer. key-or-value)))
(defn run-cpy [[_ p1 p2] state]
(assoc state p2 (get-value p1 state)))
(defn run-jnz [todo done state]
(let [[_ p1 p2] (first todo)
value (get-value p1 state)
offset (Integer. p2)]
(cond
(= 0 value) [(rest todo) (cons (first todo) done) state]
(< 0 offset) [(drop offset todo) (concat (reverse (take offset todo)) done) state]
(> 0 offset) [(concat (reverse (take (- 0 offset) done)) todo) (drop (- 0 offset) done) state])))
(defn run-inc [[_ p _] state]
(update state p #(+ 1 %)))
(defn run-dec [[_ p _] state]
(update state p #(- % 1)))
(defn run-commands [todo state]
(loop [todo todo
done []
state state]
(if (= 0 (count todo))
state
(case (first (first todo))
"cpy"
(recur (rest todo)
(cons (first todo) done)
(run-cpy (first todo) state))
"jnz"
(let [[new-todo new-done new-state] (run-jnz todo done state)]
(recur new-todo new-done new-state))
"inc"
(recur (rest todo)
(cons (first todo) done)
(run-inc (first todo) state))
"dec"
(recur (rest todo)
(cons (first todo) done)
(run-dec (first todo) state))))))
(run-commands example {"a" 0, "b" 0, "c" 0, "d" 0})
(run-commands input {"a" 0, "b" 0, "c" 0, "d" 0})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment