From 9ab7b05a9c147c983f824100c8ce3ffd6517e8b8 Mon Sep 17 00:00:00 2001 From: narimiran Date: Thu, 12 Sep 2024 16:03:06 +0200 Subject: [PATCH] day21.clj: 1.4x faster --- clojure/day21.clj | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/clojure/day21.clj b/clojure/day21.clj index e9b18d6..8f286bc 100644 --- a/clojure/day21.clj +++ b/clojure/day21.clj @@ -6,6 +6,10 @@ (def sq-size 131) (def p2-squares (quot p2-steps sq-size)) +(defn normalize [[x y]] + (+ (* 1000 (mod y sq-size)) + (mod x sq-size))) + (defn calc-total [[a b c]] (+ a @@ -27,19 +31,25 @@ (if even-step? (swap! p2 conj (count @seen-even)) (swap! p2 conj (count @seen-odd)))) - (reduce (fn [c pt] - (into c (for [[x y] (aoc/neighbours 4 pt) - :let [nb [(mod x sq-size) (mod y sq-size)]] - :when (and (not (walls nb)) - (if even-step? - (not (@seen-odd [x y])) - (not (@seen-even [x y]))))] - (do (if even-step? - (swap! seen-odd conj [x y]) - (swap! seen-even conj [x y])) - [x y])))) - #{} - current))) + (persistent! + (reduce + (fn [c nbs] + (reduce (fn [c nb] + (if even-step? + (swap! seen-odd conj nb) + (swap! seen-even conj nb)) + (conj! c nb)) + c + nbs)) + (transient #{}) + (map (fn [pt] (aoc/neighbours + 4 pt + (fn [nb] + (and (not (walls (normalize nb))) + (if even-step? + (not (@seen-odd nb)) + (not (@seen-even nb))))))) + current))))) [start] (range (+ 1 65 (* 2 sq-size)))) [@p1 (calc-total @p2)])) @@ -49,7 +59,7 @@ (let [input (aoc/parse-input input :chars) size (count input) start [(quot size 2) (quot size 2)] - walls (set (keys (aoc/grid->points input #{\#})))] + walls (aoc/grid->hashed-point-set input #{\#})] (traverse walls start)))