1 (ns adventofcode2019.intcode
2 [:require [adventofcode2019.lib :refer :all]])
4 ;; 0: function args&mem -> [mem (ctr -> ctr)]
6 (defn- decode-op [opcode]
7 (let [str-code (format "%05d" opcode)
8 flags (reverse (take 3 str-code))
9 op (vec (drop 3 str-code))
10 apply-flag (fn [flag arg]
12 \0 (fn ([] arg) ([S] (get-in S [:memory arg])))
14 \2 #(get-in % [:memory (+' arg (:relctr %))])))
17 (apply f S (map apply-flag flags args))))]
20 [\0 \1] (fn [S a b c] ; ADD
22 (assoc-in [:memory (c)] (+' (a S) (b S)))
24 [\0 \2] (fn [S a b c] ; MULT
26 (assoc-in [:memory (c)] (*' (a S) (b S)))
28 [\0 \3] (fn [S a _ _] ; IN
30 (assoc-in [:memory (a)] (first (:input S)))
31 (update :input subvec 1)
33 [\0 \4] (fn [S a _ _] ; OUT
35 (update :output conj (get-in S [:memory (a)]))
37 [\0 \5] (fn [S a b _] ; BNEQ
38 (update S :ctr (if (not= (a S) 0) (constantly (b S)) #(+ % 3))))
39 [\0 \6] (fn [S a b _] ; BEQ
40 (update S :ctr (if (= (a S) 0) (constantly (b S)) #(+ % 3))))
41 [\0 \7] (fn [S a b c] ; SLT
43 (assoc-in [:memory (c)] (if (< (a S) (b S)) 1 0))
45 [\0 \8] (fn [S a b c] ; SEQ
47 (assoc-in [:memory (c)] (if (= (a S) (b S)) 1 0))
49 [\0 \9] (fn [S a _ _] ; SREL
51 (update :relctr + (a S))
53 [\9 \9] (fn [S _ _ _] ; EXIT
54 (assoc S :exit 1))))))
56 (defn- perform-operation [{:keys [memory ctr] :as state}]
57 (let [operation (decode-op (memory ctr))
58 args (map memory [(+ 1 ctr) (+ 2 ctr) (+ 3 ctr)])]
59 (apply operation state args)))
63 (let [memory (into {} (map-indexed #(vector %1 %2) program))]
64 {:memory memory :ctr 0 :input [] :output [] :relctr 0}))
66 (merge (build-state program) settings)))
68 (defn intcode [{:as state :keys [memory output]}]
69 (cond ; quit if :exit, step and return state if :step, else loop
70 (get state :exit) {:memory memory :output output}
71 (get state :step) (perform-operation state)
72 :else (recur (perform-operation state))))