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 ;; ORs avoid returning nil
13 \0 (fn ([S] (or (get-in S [:memory arg]) 0))
16 \2 (fn ([S] (or (get-in S [:memory (+ arg (:relctr S))]) 0))
17 ([S _] (+ arg (:relctr S))))))
20 (apply f S (map apply-flag flags args))))]
23 [\0 \1] (fn [S a b c] ; ADD
25 (assoc-in [:memory (c S true)] (+' (a S) (b S)))
27 [\0 \2] (fn [S a b c] ; MULT
29 (assoc-in [:memory (c S true)] (*' (a S) (b S)))
31 [\0 \3] (fn [S a _ _] ; IN
33 (assoc-in [:memory (a S true)] (first (:input S)))
34 (update :input subvec 1)
36 [\0 \4] (fn [S a _ _] ; OUT
38 (update :output conj (or (get-in S [:memory (a S true)]) 0))
40 [\0 \5] (fn [S a b _] ; BNEQ
41 (update S :ctr (if (not= (a S) 0) (constantly (b S)) #(+ % 3))))
42 [\0 \6] (fn [S a b _] ; BEQ
43 (update S :ctr (if (= (a S) 0) (constantly (b S)) #(+ % 3))))
44 [\0 \7] (fn [S a b c] ; SLT
46 (assoc-in [:memory (c S true)] (if (< (a S) (b S)) 1 0))
48 [\0 \8] (fn [S a b c] ; SEQ
50 (assoc-in [:memory (c S true)] (if (= (a S) (b S)) 1 0))
52 [\0 \9] (fn [S a _ _] ; SREL
54 (update :relctr + (a S))
56 [\9 \9] (fn [S _ _ _] ; EXIT
57 (assoc S :exit 1))))))
59 (defn- perform-operation [{:keys [memory ctr] :as state}]
60 (let [operation (decode-op (memory ctr))
61 args (map memory [(+ 1 ctr) (+ 2 ctr) (+ 3 ctr)])]
62 (apply operation state args)))
66 (let [memory (into {} (map-indexed #(vector %1 %2) program))]
67 {:memory memory :ctr 0 :input [] :output [] :relctr 0}))
69 (merge (build-state program) settings)))
71 (defn intcode-until [pred state]
72 (as-> (assoc state :step true) it
74 (drop-while #(or (not (:exit %)) (pred %)) it)
78 (defn intcode [{:as state :keys [memory output]}]
79 (cond ; quit if :exit, step and return state if :step, else loop
80 (get state :exit) {:memory memory :output output :exit true}
81 (get state :step) (perform-operation state)
82 :else (recur (perform-operation state))))