Refactor Intcode into a library
[adventofcode2019.git] / src / adventofcode2019 / intcode.clj
CommitLineData
c0464c3a
JK
1(ns adventofcode2019.intcode
2 [:require [adventofcode2019.lib :refer :all]])
3
4;; 0: function args&mem -> [mem (ctr -> ctr)]
5;; 1: number of args
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]
11 (case flag
12 \0 (fn ([] arg) ([S] (get-in S [:memory arg])))
13 \1 (constantly arg)
14 \2 #(get-in % [:memory (+' arg (:relctr %))])))
15 with-flags (fn [f]
16 (fn [S & args]
17 (apply f S (map apply-flag flags args))))]
18 (with-flags
19 (case op
20 [\0 \1] (fn [S a b c] ; ADD
21 (-> S
22 (assoc-in [:memory (c)] (+' (a S) (b S)))
23 (update :ctr + 4)))
24 [\0 \2] (fn [S a b c] ; MULT
25 (-> S
26 (assoc-in [:memory (c)] (*' (a S) (b S)))
27 (update :ctr + 4)))
28 [\0 \3] (fn [S a _ _] ; IN
29 (-> S
30 (assoc-in [:memory (a)] (first (:input S)))
31 (update :input subvec 1)
32 (update :ctr + 2)))
33 [\0 \4] (fn [S a _ _] ; OUT
34 (-> S
35 (update :output conj (get-in S [:memory (a)]))
36 (update :ctr + 2)))
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
42 (-> S
43 (assoc-in [:memory (c)] (if (< (a S) (b S)) 1 0))
44 (update :ctr + 4)))
45 [\0 \8] (fn [S a b c] ; SEQ
46 (-> S
47 (assoc-in [:memory (c)] (if (= (a S) (b S)) 1 0))
48 (update :ctr + 4)))
49 [\0 \9] (fn [S a _ _] ; SREL
50 (-> S
51 (update :relctr + (a S))
52 (update :ctr + 2)))
53 [\9 \9] (fn [S _ _ _] ; EXIT
54 (assoc S :exit 1))))))
55
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)))
60
61(defn build-state
62 ([program]
63 (let [memory (into {} (map-indexed #(vector %1 %2) program))]
64 {:memory memory :ctr 0 :input [] :output [] :relctr 0}))
65 ([program settings]
66 (merge (build-state program) settings)))
67
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))))