Skip to content

Commit a4613a7

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

File tree

1 file changed

+32
-27
lines changed

1 file changed

+32
-27
lines changed

clojure/day23.clj

+32-27
Original file line numberDiff line numberDiff line change
@@ -18,32 +18,34 @@
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 \.) (let [nbs (aoc/neighbours
23+
4 pt
24+
(fn [[nx ny]]
25+
(and (not (seen [nx ny]))
26+
(not (#{\#} ((trails ny) nx))))))]
27+
(recur (reduce (fn [s nb] (conj s [nb seen']))
28+
stack'
29+
nbs)
30+
longest))
2731

2832
:let [pt' (if (= curr \>) [(inc x) y] [x (inc y)])]
2933
(seen pt') (recur stack' longest)
3034

3135
(recur (conj stack' [pt' seen']) longest)))))
3236

3337

34-
35-
(defn int-hash [x y]
36-
(+ (* 150 x) y))
37-
3838
(defn compress-graph [trails]
3939
(let [adjacencies (atom (i/int-map))
40-
size (count trails)]
40+
size (count trails)
41+
int-hash (fn [x y] (+ (* 150 x) y))]
4142
(doseq [[y row] (map-indexed vector trails)
4243
[x c] (map-indexed vector row)
4344
:when (not= \# c)
44-
[nx ny] (aoc/neighbours 4 [x y])
45-
:when (and (aoc/inside? size nx ny)
46-
(not= \# ((trails ny) nx)))]
45+
[nx ny] (aoc/neighbours 4 [x y]
46+
(fn [[nx ny]]
47+
(and (aoc/inside? size nx ny)
48+
(not= \# ((trails ny) nx)))))]
4749
(swap! adjacencies update (int-hash x y) assoc (int-hash nx ny) 1))
4850
(doseq [pt (keys @adjacencies)
4951
:let [nbs (@adjacencies pt)]
@@ -74,24 +76,27 @@
7476
seen' (conj seen pt)]
7577
(= pt exit) (recur stack' (max longest score))
7678

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)]))
79+
(recur (reduce (fn [s [nb cost]]
80+
(if (and (not (seen nb))
81+
(if (= 3 (count (adjacencies pt)))
82+
;; if on a perimeter, go only right and down
83+
;; makes everything 3x faster
84+
(or (> nb pt)
85+
(> (mod nb 150) (mod pt 150)))
86+
true))
87+
(conj s [nb seen' (+ score cost)])
88+
s))
89+
stack'
90+
(adjacencies pt))
8791
longest)))))
8892

8993

9094
(defn solve [input-file]
9195
(let [trails (aoc/parse-input input-file :chars)
92-
adjacencies (compress-graph trails)]
93-
[(part-1 trails)
94-
(part-2 adjacencies)]))
96+
adjacencies (compress-graph trails)
97+
p1 (future (part-1 trails))
98+
p2 (future (part-2 adjacencies))]
99+
[@p1 @p2]))
95100

96101

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

0 commit comments

Comments
 (0)