aoc2023/3.rkt

56 lines
1.8 KiB
Racket

#lang curly-fn racket
(require "scripts/aoc.rkt")
;; solution for day 3
(define *delta* '((0 . 1) (1 . 1) (1 . 0)
(1 . -1) (0 . -1) (-1 . -1)
(-1 . 0) (-1 . 1)))
(define (posn+ a b)
(cons (+ (car a) (car b))
(+ (cdr a) (cdr b))))
(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)))
(define (part2 input)
(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)))))
(define (parse fname)
(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)
(module+ main
(define input (parse "inputs/3"))
(answer 3 1 (time (part1 input)))
(answer 3 2 (time (part2 input)))
(displayln "meow"))