Advertisement
luorduz

advent-22-11

Dec 12th, 2022
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Clojure 2.02 KB | Source Code | 0 0
  1. (defn make-monkey [[_ items op check pass fail]] {
  2.   "items" (as-> items i
  3.     (clojure.string/split i #":") (second i)
  4.     (clojure.string/split i #",")
  5.     (map #(clojure.string/replace % " " "") i)
  6.     (map #(Integer/parseInt %) i)
  7.   ),
  8.   "op" (as-> op o
  9.     (clojure.string/split o #"=")
  10.     (second o)
  11.     (clojure.string/split o #" ")
  12.     (remove clojure.string/blank? o)
  13.     ((fn [[arg1 op arg2]] (format
  14.       "#(%s %s %s)"
  15.       op
  16.       (if (= "old" arg1) "%" arg1)
  17.       (if (= "old" arg2) "%" arg2)
  18.     )) o)
  19.     (read-string o)
  20.     (eval o)
  21.   )
  22.   "check" (-> check (clojure.string/split #" ") last (Integer/parseInt))
  23.   "pass" (-> pass (clojure.string/split #" ") last (Integer/parseInt))
  24.   "fail" (-> fail (clojure.string/split #" ") last (Integer/parseInt))
  25.   "history" 0
  26. })
  27.  
  28. (defn step [[monkeys monkey] item] (let [
  29.   item ((monkey "op") item)
  30.   tar (if (zero? (mod item (monkey "check"))) "pass" "fail")
  31.   target (monkey tar)
  32.   items (get-in monkeys [target "items"])
  33.   history (inc (monkey "history"))
  34. ] [
  35.   (assoc-in monkeys [target "items"] (conj items item))
  36.   (assoc monkey "history" history)
  37. ]))
  38.  
  39. (defn turn [monkeys pos]
  40.   (->>
  41.     (reduce step [monkeys (get monkeys pos)] (get-in monkeys [pos "items"]))
  42.     ((fn [[monkeys monkey]] (assoc monkeys pos (assoc monkey "items" []))))
  43. ))
  44.  
  45. (defn round [monkeys]
  46.   (reduce turn monkeys (range (count monkeys)))
  47. )
  48.  
  49. (defn do-task [rounds monkeys]
  50.   (->> monkeys
  51.     vec (iterate round) (take rounds) last (map #(% "history")) sort (take-last 2) (apply *) println)
  52. )
  53.  
  54. (with-open [rdr (clojure.java.io/reader "monkeys.in")] (let [
  55.   monkeys (->> rdr
  56.     line-seq
  57.     (partition-by #(= "" %))
  58.     (remove #(= 1 (count %)))
  59.     (map make-monkey))
  60. ](->> monkeys
  61.   (map (fn [monkey] (assoc monkey "op" #(quot ((monkey "op") %) 3))))
  62.   (do-task 21)
  63. )
  64. (->> monkeys
  65.   (vector (apply * (map #(% "check") monkeys)))
  66.   ((fn [[worry monkeys]] (map (fn [monkey] (assoc monkey "op" #(mod ((monkey "op") %) worry))) monkeys)))
  67.   (do-task 10001)
  68. )))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement