SHARE
TWEET

Untitled

a guest Dec 2nd, 2019 85 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns aoc2019.day2
  2.   (:require [clojure.string :as s]))
  3.  
  4. (def ops {1 +
  5.           2 *})
  6.  
  7. (defn read-input []
  8.   (-> (slurp "resources/day2.txt")
  9.       (s/trim-newline)
  10.       (s/split #",")
  11.       (->> (map #(Integer/parseInt %)))))
  12.  
  13. (defn calc-result [prog op]
  14.   (let [cmd (ops (first op))
  15.         arg1 (nth prog (nth op 1))
  16.         arg2 (nth prog (nth op 2))
  17.         result-pos (last op)]
  18.     (assoc prog result-pos (cmd arg1 arg2))))
  19.  
  20. (defn run [prog pos]
  21.   (let [op (take 4 (drop pos prog))]
  22.     (if (= 99 (first op))
  23.       (first prog)
  24.       (run (calc-result prog op) (+ pos 4)))))
  25.  
  26. (defn init [input n v]
  27.   (-> input
  28.       vec
  29.       (assoc 1 n)
  30.       (assoc 2 v)))
  31.  
  32. (def target 19690720)
  33.  
  34. (defn find-args [input]
  35.   (loop [n 0 v 0]
  36.     (let [res (run (init input n v) 0)]
  37.       (if (= res target)
  38.         (+ (* n 100) v)
  39.         (if (= 99 v)
  40.           (recur (inc n) 0)
  41.           (recur n (inc v)))))))
  42.  
  43. (defn solve-p1 []
  44.   (let [input (read-input)
  45.         prog (init input 12 2)]
  46.     (run prog 0)))
  47.  
  48. (defn solve-p2 []
  49.   (let [input (read-input)]
  50.     (find-args input)))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top