clean up day 2 solution with fancy stuff

This commit is contained in:
xenia 2020-12-02 05:08:00 -05:00
parent c278b60801
commit f54047466a
1 changed files with 11 additions and 9 deletions

20
2.rkt
View File

@ -1,24 +1,26 @@
#lang racket
#lang curly-fn racket
(require "scripts/aoc.rkt")
;; solution for day 2
;; checks if the count of the given character in the password is between lmin and lmax
(define (password-valid-part1? lmin lmax char password)
(<= lmin (count (curry char=? char) (string->list password)) lmax))
(<= lmin (~>> password string->list (count #{char=? char %})) lmax))
;; checks that exactly one of the positions specified by a and b contain char
(define (password-valid-part2? a b char password)
(define pwd-chars (string->list password))
(xor (char=? (string-ref password (sub1 a)) char)
(char=? (string-ref password (sub1 b)) char)))
(define check #{char=? (string-ref password (sub1 %)) char})
(xor (check a) (check b)))
(define (calculate valid-proc input)
(for/sum ([line (in-list input)])
(match line
[(pregexp #px"^([0-9]+)\\-([0-9]+) (.): (.*?)$" (list _ lmin lmax char password))
(if (valid-proc (string->number lmin) (string->number lmax)
(string-ref char 0) password) 1 0)]
[_ (error "failed to parse" line)])))
[(pregexp #px"^([0-9]+)\\-([0-9]+) (.): (.*?)$"
(list _ (app string->number lmin) (app string->number lmax)
(app #{string-ref % 0} char) password))
(if (valid-proc lmin lmax char password) 1 0)]
[_ (error "not shonks 🦈📉" line)])))
(module+ main
(define input (file->lines "inputs/2"))