Day 09: Use sets.

This commit is contained in:
Jonathan Chan 2021-12-08 23:17:22 -08:00
parent e4dd2b58f4
commit 59b8087029
1 changed files with 16 additions and 13 deletions

View File

@ -1,6 +1,7 @@
#lang curly-fn racket #lang curly-fn racket
(require racket/set "../lib.rkt") (require racket/set
"../lib.rkt")
(define input (define input
(~>> (problem-input 9) (~>> (problem-input 9)
@ -27,18 +28,20 @@
(grid-ref input (car %) (cdr %))} (grid-ref input (car %) (cdr %))}
(neighbours row col))) (neighbours row col)))
(define (highers row col) (define (basinic seen loc)
(filter #{and (< (grid-ref input row col) (list->set
(grid-ref input (car %) (cdr %) -inf.0) (filter #{and (< (grid-ref input (car %) (cdr %)) 9)
9)} (not (set-member? seen %))}
(neighbours row col))) (neighbours (car loc) (cdr loc)))))
(define (basin unseen seen) (define (basin row col)
(match unseen (let loop ([unseen (set (cons row col))]
['() (unique seen)] [seen (set)])
[(list (and hd (cons row col)) tl ...) (if (set-empty? unseen)
(basin (append tl (highers row col)) (set-count seen)
(cons hd seen))])) (let ([loc (set-first unseen)])
(loop (set-union (basinic seen loc) (set-rest unseen))
(set-add seen loc))))))
(define-values (part1 part2) (define-values (part1 part2)
(for/fold ([risk 0] (for/fold ([risk 0]
@ -50,7 +53,7 @@
([col (range cols)]) ([col (range cols)])
(if (low? row col) (if (low? row col)
(values (+ (add1 (grid-ref input row col)) risk) (values (+ (add1 (grid-ref input row col)) risk)
(cons (length (basin `((,row . ,col)) '())) basins)) (cons (basin row col) basins))
(values risk basins))))) (values risk basins)))))
(show-solution part1 part2) (show-solution part1 part2)