Skip to content

Commit 872108e

Browse files
committed
day23.clj: 1.75x faster
1 parent 32e2610 commit 872108e

File tree

1 file changed

+30
-27
lines changed

1 file changed

+30
-27
lines changed

clojure/day23.clj

+30-27
Original file line numberDiff line numberDiff line change
@@ -18,32 +18,32 @@
1818
(= pt end) (recur stack' (max longest (count seen)))
1919

2020
:let [curr ((trails y) x)
21-
seen' (conj seen pt)
22-
nbs (for [[nx ny] (aoc/neighbours 4 pt)
23-
:when (and (not (seen [nx ny]))
24-
(not (#{\#} ((trails ny) nx))))]
25-
[[nx ny] seen'])]
26-
(= curr \.) (recur (into stack' nbs) longest)
21+
seen' (conj seen pt)]
22+
(= curr \.) (recur (reduce (fn [s nb] (conj s [nb seen']))
23+
stack'
24+
(aoc/neighbours 4 pt
25+
(fn [[nx ny]]
26+
(and (not (seen [nx ny]))
27+
(not (#{\#} ((trails ny) nx)))))))
28+
longest)
2729

2830
:let [pt' (if (= curr \>) [(inc x) y] [x (inc y)])]
2931
(seen pt') (recur stack' longest)
3032

3133
(recur (conj stack' [pt' seen']) longest)))))
3234

3335

34-
35-
(defn int-hash [x y]
36-
(+ (* 150 x) y))
37-
3836
(defn compress-graph [trails]
3937
(let [adjacencies (atom (i/int-map))
40-
size (count trails)]
38+
size (count trails)
39+
int-hash (fn [x y] (+ (* 150 x) y))]
4140
(doseq [[y row] (map-indexed vector trails)
4241
[x c] (map-indexed vector row)
4342
:when (not= \# c)
44-
[nx ny] (aoc/neighbours 4 [x y])
45-
:when (and (aoc/inside? size nx ny)
46-
(not= \# ((trails ny) nx)))]
43+
[nx ny] (aoc/neighbours 4 [x y]
44+
(fn [[nx ny]]
45+
(and (aoc/inside? size nx ny)
46+
(not= \# ((trails ny) nx)))))]
4747
(swap! adjacencies update (int-hash x y) assoc (int-hash nx ny) 1))
4848
(doseq [pt (keys @adjacencies)
4949
:let [nbs (@adjacencies pt)]
@@ -74,24 +74,27 @@
7474
seen' (conj seen pt)]
7575
(= pt exit) (recur stack' (max longest score))
7676

77-
(recur (into stack'
78-
(for [[nb cost] (adjacencies pt)
79-
:when (not (seen nb))
80-
:when (if (= 3 (count (adjacencies pt)))
81-
;; if on a perimeter, go only right and down
82-
;; makes everything 3x faster
83-
(or (> nb pt)
84-
(> (mod nb 150) (mod pt 150)))
85-
true)]
86-
[nb seen' (+ score cost)]))
77+
(recur (reduce (fn [s [nb cost]]
78+
(if (and (not (seen nb))
79+
(if (= 3 (count (adjacencies pt)))
80+
;; if on a perimeter, go only right and down
81+
;; makes everything 3x faster
82+
(or (> nb pt)
83+
(> (mod nb 150) (mod pt 150)))
84+
true))
85+
(conj s [nb seen' (+ score cost)])
86+
s))
87+
stack'
88+
(adjacencies pt))
8789
longest)))))
8890

8991

9092
(defn solve [input-file]
9193
(let [trails (aoc/parse-input input-file :chars)
92-
adjacencies (compress-graph trails)]
93-
[(part-1 trails)
94-
(part-2 adjacencies)]))
94+
adjacencies (compress-graph trails)
95+
p1 (future (part-1 trails))
96+
p2 (future (part-2 adjacencies))]
97+
[@p1 @p2]))
9598

9699

97100
(solve (aoc/read-file 23))

0 commit comments

Comments
 (0)