Advent of Code 2020 solutions in Racket, I guess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.8 KiB

#lang racket
(require "lib/common.rkt")
;; naive solution: manual BSP
(define (lower-half lst)
(take lst (quotient (length lst) 2)))
(define (upper-half lst)
(drop lst (quotient (length lst) 2)))
(define (pass->seat str)
(define (row-bsp row)
(for/fold ([rng (range 0 127)])
([ch (in-string row)])
(match ch
[#\F (lower-half rng)]
[#\B (upper-half rng)]))))
(define (col-bsp col)
(for/fold ([rng (range 0 8)])
([ch (in-string col)])
(match ch
[#\L (lower-half rng)]
[#\R (upper-half rng)]))))
(define row-pass (substring str 0 7))
(define col-pass (substring str 7 10))
(cons (add1 (row-bsp row-pass)) (col-bsp col-pass)))
(define (seat->id seat)
(+ (* (car seat) 8) (cdr seat)))
;; big brain solution: it's just a binary string
(define (pass->id str)
(for/fold ([id 0])
([ch (in-string str)])
(+ (* 2 id)
(case ch
[(#\F #\L) 0]
[(#\B #\R) 1]))))
(define (day5a in)
(apply max (map (compose1 seat->id pass->seat) in)))
(define (day5b in)
(define ids (map (compose1 seat->id pass->seat) in))
(first (memf (lambda (id)
(and (not (member id ids))
(member (add1 id) ids)
(member (sub1 id) ids)))
(range (apply min ids)
(apply max ids)))))
(module+ main
(call-with-input-file "data/day5.txt"
(lambda (prt)
(define input (port->lines prt))
(answer 5 1 (day5a input))
(answer 5 2 (day5b input)))))
(module+ test
(require rackunit)
(call-with-input-file "data/day5.txt"
(lambda (prt)
(define input (port->lines prt))
(check-equal? (day5a input) 935)
(check-equal? (day5b input) 743))))