2023-12-03 05:28:48 +00:00
|
|
|
#lang curly-fn racket
|
|
|
|
|
|
|
|
(require "scripts/aoc.rkt")
|
|
|
|
|
|
|
|
;; solution for day 3
|
|
|
|
|
2023-12-03 05:52:34 +00:00
|
|
|
(define *delta* '((0 . 1) (1 . 1) (1 . 0)
|
|
|
|
(1 . -1) (0 . -1) (-1 . -1)
|
|
|
|
(-1 . 0) (-1 . 1)))
|
2023-12-03 05:28:48 +00:00
|
|
|
|
2023-12-03 05:52:34 +00:00
|
|
|
(define (posn+ a b)
|
|
|
|
(cons (+ (car a) (car b))
|
|
|
|
(+ (cdr a) (cdr b))))
|
2023-12-03 05:28:48 +00:00
|
|
|
|
2023-12-03 05:52:34 +00:00
|
|
|
(define (part1 input)
|
|
|
|
(define numbers
|
|
|
|
(for/set ([(pos elem) (in-hash input)]
|
|
|
|
#:when (char? elem)
|
|
|
|
[d (in-list *delta*)]
|
|
|
|
#:do [(define neigh (hash-ref input (posn+ pos d) #f))]
|
|
|
|
#:when (list? neigh))
|
|
|
|
neigh))
|
|
|
|
(for/sum ([n (in-set numbers)])
|
|
|
|
(third n)))
|
2023-12-03 05:28:48 +00:00
|
|
|
|
|
|
|
(define (part2 input)
|
2023-12-03 05:52:34 +00:00
|
|
|
(for/sum ([(pos elem) (in-hash input)]
|
|
|
|
#:when (equal? elem #\*)
|
|
|
|
#:do [(define neighs
|
|
|
|
(for/set ([d (in-list *delta*)]
|
|
|
|
#:do [(define neigh (hash-ref input (posn+ pos d) #f))]
|
|
|
|
#:when (list? neigh))
|
|
|
|
neigh))]
|
|
|
|
#:when (= 2 (set-count neighs)))
|
|
|
|
(apply * (map third (set->list neighs)))))
|
2023-12-03 05:28:48 +00:00
|
|
|
|
|
|
|
(define (parse fname)
|
2023-12-03 05:52:34 +00:00
|
|
|
(define elements (make-hash))
|
|
|
|
(for ([line (in-lines (open-input-file fname))] [y (in-naturals)]
|
|
|
|
#:do [(for ([posn (in-list (regexp-match-positions* #px"[0-9]+" line))]
|
|
|
|
#:do [(match-define (cons xmin xmax) posn)]
|
|
|
|
[x (in-range xmin xmax)])
|
|
|
|
(hash-set! elements (cons y x)
|
|
|
|
(list y xmin (string->number (substring line xmin xmax)))))]
|
|
|
|
[chr (in-string line)] [x (in-naturals)]
|
|
|
|
#:unless (equal? chr #\.)
|
|
|
|
#:unless (char-numeric? chr))
|
|
|
|
(hash-set! elements (cons y x) chr))
|
|
|
|
elements)
|
2023-12-03 05:28:48 +00:00
|
|
|
|
|
|
|
(module+ main
|
|
|
|
(define input (parse "inputs/3"))
|
|
|
|
(answer 3 1 (time (part1 input)))
|
|
|
|
(answer 3 2 (time (part2 input)))
|
|
|
|
(displayln "meow"))
|