Last active
December 7, 2019 17:02
-
-
Save MarcoNicolodi/b4bca7b9f1db873920a99470b41e1d0d to your computer and use it in GitHub Desktop.
advent of code 2019 day 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns advent-of-code-2019.day-2 | |
(:require [clojure.string :as str])) | |
(defn halt? [[op & _]] (= op :halt)) | |
(defn pointer+memory->instruction [pointer memory] | |
(let [int->opcode {1 + 2 * 99 :halt} | |
op (nth memory pointer) | |
in1 (nth memory (inc pointer) 0) | |
in2 (nth memory (+ 2 pointer) 0) | |
output-pos (nth memory (+ 3 pointer) 0)] | |
[(int->opcode op) (nth memory in1 nil) (nth memory in2 nil) output-pos])) | |
(defn execute [memory [op in1 in2 out-pos]] | |
(assoc memory out-pos (op in1 in2))) | |
(defn operator [memory pointer] | |
(loop [pointer pointer memory memory] | |
(let [instruction (pointer+memory->instruction pointer memory)] | |
(if (halt? instruction) | |
memory | |
(recur (+ pointer 4) (execute memory instruction)))))) | |
(defn wire->internal [in] | |
(->> (str/split in #",") | |
(mapv (comp #(Integer/parseInt %) str/trim-newline str/trim)))) | |
(defn internal->wire [out] | |
(str/join #"," out)) | |
(defn with-replacements [memory & replacements] | |
(reduce (fn [acc [position value]] (assoc acc position value)) | |
memory | |
replacements)) | |
(defn notify-when [memory pred notify-fn] | |
(when (pred memory) (notify-fn))) | |
(defn main-part2 [] | |
(let [in (wire->internal (slurp "day_2.in"))] | |
(for [noun (range 100) verb (range 100)] | |
(-> in | |
(with-replacements [1 noun] [2 verb]) | |
(operator 0) | |
(notify-when #(= (first %) 19690720) | |
#(spit "day_2.out" (+ verb (* 100 noun)))))))) | |
(defn main-part1 [] | |
(-> (slurp "day_2.in") | |
wire->internal | |
(operator 1) | |
internal->wire | |
(->> (spit "day_2.out")))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment