Last active
December 4, 2023 20:13
-
-
Save qookei/cc0c0b95ade8432b71c18c3734ead40f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(use-modules (ice-9 textual-ports) (srfi srfi-1) (srfi srfi-26) | |
(ice-9 match) (ice-9 format) (ice-9 hash-table)) | |
(define (process-line line) | |
(match-let ([(id our winning) | |
(map (cut string-tokenize <> char-set:digit) | |
(string-split line (char-set #\| #\:)))]) | |
(cons (string->number (car id)) | |
(cons (map string->number our) | |
(map string->number winning))))) | |
(define (read-input) | |
(let ([line (get-line (current-input-port))]) | |
(if (eof-object? line) | |
'() | |
(cons (process-line line) | |
(read-input))))) | |
(define (card-matches card-cons) | |
(length (lset-intersection eqv? | |
(cadr card-cons) | |
(cddr card-cons)))) | |
(define (cards-won-from-card card-cons) | |
(cons (car card-cons) | |
(iota (card-matches card-cons) | |
(1+ (car card-cons))))) | |
(define (part1 cards-alist) | |
(fold + 0 | |
(map (λ (card-cons) | |
(floor (expt 2 (1- (card-matches card-cons))))) | |
cards-alist))) | |
(define (part2 cards-alist) | |
(let ([counts (make-list (length cards-alist) 1)] | |
[wins (map cards-won-from-card cards-alist)]) | |
(for-each | |
(λ (card-cons) | |
(for-each | |
(λ (won-id) | |
(list-set! counts (1- won-id) | |
(+ (list-ref counts (1- won-id)) | |
(list-ref counts (1- (car card-cons)))))) | |
(cdr card-cons))) | |
wins) | |
(fold + 0 counts))) | |
(let ([cards-alist (read-input)]) | |
(format #t "Part 1: ~a~%" (part1 cards-alist)) | |
(format #t "Part 2: ~a~%" (part2 cards-alist))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment