1 (ns adventofcode2019.day05
2 [:require [adventofcode2019.lib :refer :all]
3 [clojure.string :as str]])
5 ;; 0: function args&mem -> [mem (ctr -> ctr)]
7 (def operations {1 [(fn [a b c mem]
8 [(assoc mem c (+ a b)) #(+ % 4)])
11 [(assoc mem c (* a b)) #(+ % 4)])
14 [(assoc mem a (parse-int (read-line))) #(+ % 2)])
21 [mem (if (not= a 0) (constantly b) #(+ % 3))])
24 [mem (if (= a 0) (constantly b) #(+ % 3))])
27 [(assoc mem c (if (< a b) 1 0)) #(+ % 4)])
30 [(assoc mem c (if (= a b) 1 0)) #(+ % 4)])
33 ;; FIXME: sorry about the dropped forms i didn't want to fix it properly
34 ;; the problem is that flags don't apply to certain args for certain ops
35 (defn decode-op [opcode]
36 (let [str-code (format "%05d" opcode)
37 [f3 f2 f1] (map #(= \1 %) (take 3 str-code))
38 op (parse-int (str/join (drop 3 str-code)))
39 [operation arg-ct] (operations op)]
41 1 #(operation #_((if f1 identity %1) %2) %2 %1)
42 2 #(operation ((if f1 identity %1) %2)
43 ((if f2 identity %1) %3) %1)
44 3 #(operation ((if f1 identity %1) %2)
45 ((if f2 identity %1) %3)
46 #_((if f3 identity %1) %4) %4 %1))
49 (defn perform-operation [program counter]
50 (let [opcode (program counter)
51 [operation arg-ct] (decode-op opcode)
52 args (->> (iterate inc counter)
56 (let [[program ctr-update] (apply operation program args)]
57 [program (ctr-update counter)])))
59 (defn intcode [program]
60 (loop [[program counter] [program 0]]
61 (let [opcode (program counter)]
64 (recur (perform-operation program counter))))))
67 (let [input (mapv parse-int (get-list-from-file (input-file) #","))]