day 5: cleaned up version

This commit is contained in:
xenia 2020-12-05 00:27:13 -05:00
parent e5af484c65
commit 349942150d
1 changed files with 18 additions and 18 deletions

36
5.rkt
View File

@ -7,29 +7,29 @@
;; helper functions here
(define (part1 input)
(apply max
(for/list ([line (in-list input)])
(match-define (list _ rowstr colstr) (regexp-match #px"^([FB]{7})([LR]{3})$" line))
(define row (string->number (string-replace (string-replace rowstr "F" "0") "B" "1") 2))
(define col (string->number (string-replace (string-replace colstr "L" "0") "R" "1") 2))
(+ (* row 8) col))))
(apply max input))
(define (part2 input)
(define seats
(for/list ([line (in-list input)])
(match-define (list _ rowstr colstr) (regexp-match #px"^([FB]{7})([LR]{3})$" line))
(define row (string->number (string-replace (string-replace rowstr "F" "0") "B" "1") 2))
(define col (string->number (string-replace (string-replace colstr "L" "0") "R" "1") 2))
(+ (* row 8) col)))
(for/first ([id (in-range (apply min seats) (apply max seats))]
#:when (and (not (member id seats))
(member (add1 id) seats)
(member (sub1 id) seats)))
(for/first ([id (in-range (apply min input) (apply max input))]
#:when (and (not (member id input))
(member (add1 id) input)
(member (sub1 id) input)))
id))
(module+ main
(define input (file->lines "inputs/5"))
(define input (for/list ([line (in-list (file->lines "inputs/5"))])
;; ok what is this fuckery???
;; the trick is the whole number can just be treated as binary
;; first, notice that the entry is a concatenation of row and column, and both
;; are basically binary numbers, B and R are a 1 digit and F and L are a 0 digit
;; finally... the ID is <first part> * 8 + <second part>, and conveniently the
;; second part is 3 digits
;; so we parse the whole thing as a single binary number. rather than
;; string-replacing the chars and then number->string with radix 2, i used a
;; manual fold to build the number
(for/fold ([val 0]) ([char (in-string line)])
(+ (* 2 val) (if ((or/c #\B #\R) char) 1 0)))))
;; part 1
(answer 5 1 (part1 input))