1
0
Fork 0

Day 15: Now runs in about 10s.

This commit is contained in:
Jonathan Chan 2021-12-15 20:41:28 -08:00 committed by Jonathan Chan
parent 4a6bb35627
commit 05ac638ac2
1 changed files with 10 additions and 19 deletions

View File

@ -3,6 +3,8 @@
(require graph (require graph
(except-in "../lib.rkt" transpose)) (except-in "../lib.rkt" transpose))
(struct posn (row col) #:transparent)
(define input (define input
(for/vector ([row (problem-input 15)]) (for/vector ([row (problem-input 15)])
(for/vector ([col (string->list row)]) (for/vector ([col (string->list row)])
@ -21,29 +23,18 @@
(filter #{and (<= 0 (car %) (sub1 dim)) (<= 0 (cdr %) (sub1 dim))} (filter #{and (<= 0 (car %) (sub1 dim)) (<= 0 (cdr %) (sub1 dim))}
`((,(add1 row) . ,col) (,(sub1 row) . ,col) (,row . ,(add1 col)) (,row . ,(sub1 col))))) `((,(add1 row) . ,col) (,(sub1 row) . ,col) (,row . ,(add1 col)) (,row . ,(sub1 col)))))
(for/fold ([weights (hash '(0 . 0) 0)]
#:result (printf "Part 1: ~a\n" (hash-ref weights `(,(sub1 dim) . ,(sub1 dim)))))
([diag (range* 0 (+ dim dim))])
(for/fold ([weights weights])
([row (range* 0 diag 1)]
[col (range* diag 0 -1)]
#:when (and (< row dim) (< col dim)))
(for/fold ([weights weights])
([adj (adjs dim row col)])
(match-let* ([(cons row* col*) adj]
[weight (+ (grid-ref row* col*)
(hash-ref weights (cons row col)))])
(hash-update weights adj #{if (< weight %) weight %} +inf.0)))))
(define (make-graph dim) (define (make-graph dim)
(define graph (weighted-graph/directed '())) (define graph (weighted-graph/directed '()))
(for* ([row (range dim)] (for* ([row (range dim)]
[col (range dim)] [col (range dim)]
[adj (adjs dim row col)]) [adj (adjs dim row col)])
(add-directed-edge! graph (cons row col) adj (grid-ref (car adj) (cdr adj)))) (add-directed-edge! graph (posn row col)
(displayln "Graph created.") (posn (car adj) (cdr adj))
(grid-ref (car adj) (cdr adj))))
graph) graph)
(let*-values ([(dim) (* dim 5)] (define (shortest-path dim)
[(weights paths) (dijkstra (make-graph dim) '(0 . 0))]) (let*-values ([(weights paths) (dijkstra (make-graph dim) (posn 0 0))])
(printf "Part 2: ~a\n" (hash-ref weights `(,(sub1 dim) . ,(sub1 dim))))) (hash-ref weights (posn (sub1 dim) (sub1 dim)))))
(show-solution (shortest-path dim) (shortest-path (* dim 5)))