Advertisement
tiagoespinha

Advent of Code 2nd Puzzle

Dec 2nd, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     (defn- load-code
  2.       []
  3.       (into [] (map #(-> %
  4.                          (clojure.string/trim)
  5.                          (Integer/parseInt))
  6.                     (clojure.string/split (slurp "resources/puzzle2.txt") #","))))
  7.    
  8.     (defn- operation
  9.       [operation-fn first-value second-value result-idx program-code]
  10.       (swap!
  11.        program-code
  12.        #(assoc
  13.          %
  14.          result-idx
  15.          (operation-fn first-value second-value))))
  16.    
  17.     (defn- addition
  18.       [first-value second-value result-idx program-code]
  19.       (operation + first-value second-value result-idx program-code))
  20.    
  21.     (defn- multiplication
  22.       [first-value second-value result-idx program-code]
  23.       (operation * first-value second-value result-idx program-code))
  24.    
  25.     (defn- calculate-output-for-noun-and-verb
  26.       [noun verb]
  27.       (let [program-code (atom (load-code))
  28.             idx (atom 0)]
  29.         (swap! program-code #(assoc % 1 noun 2 verb))
  30.         (while (not= 99 (nth @program-code @idx))
  31.           (let [operation (nth @program-code @idx)
  32.                 first-value (nth @program-code (nth @program-code (+ 1 @idx)))
  33.                 second-value (nth @program-code (nth @program-code (+ 2 @idx)))
  34.                 result-idx (nth @program-code (+ 3 @idx))]
  35.              (cond
  36.                (= operation 1) (addition first-value second-value result-idx program-code)
  37.                (= operation 2) (multiplication first-value second-value result-idx program-code)))
  38.           (swap! idx #(+ % 4)))
  39.         (first @program-code)))
  40.      
  41.     (defn run-pt1
  42.       []
  43.       (prn (calculate-output-for-noun-and-verb 12 2)))
  44.    
  45.     (defn run-pt2
  46.       []
  47.       (loop [noun 99 verb 99]
  48.         (cond
  49.           (= noun -1)(throw (Exception. "Did not find a solution."))
  50.           (= 19690720 (calculate-output-for-noun-and-verb noun verb)) (identity {:noun noun :verb verb})
  51.           (= verb 0) (recur (dec noun) 99)
  52.           :else (recur noun (dec verb)))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement