Created
December 15, 2023 13:25
-
-
Save qookei/897dd704200daa13cd98fd695e78f70d to your computer and use it in GitHub Desktop.
This file contains 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 (srfi srfi-1) (ice-9 textual-ports) | |
(ice-9 format) (srfi srfi-26) (ice-9 match) | |
(srfi srfi-43)) | |
(define (read-input) | |
(string-split (get-line (current-input-port)) #\,)) | |
(define (hash str) | |
(string-fold | |
(λ (chr prev) | |
(remainder (* 17 (+ prev | |
(char->integer chr))) | |
256)) | |
0 str)) | |
(define (%process-item item) | |
(let ([parts (string-split item (char-set #\= #\-))]) | |
(cons (car parts) | |
(string->number (cadr parts))))) | |
(define (part1 input) | |
(fold + 0 (map hash input))) | |
(define (part2 input) | |
(let ([slots (make-vector 256 '())] | |
[parts (map %process-item input)]) | |
(for-each | |
(λ (item) | |
(let* ([slot-no (hash (car item))] | |
[slotv (vector-ref slots slot-no)]) | |
(vector-set! | |
slots | |
slot-no | |
(match item | |
[(k . #f) (assoc-remove! slotv k)] | |
[(k . v) (assoc-set! slotv k v)])))) | |
parts) | |
(vector-fold | |
(λ (i prev slot) | |
(+ prev | |
(fold + 0 | |
(map (cut * (1+ i) <...>) | |
(map cdr slot) | |
(iota (length slot) (length slot) -1))))) | |
0 slots))) | |
(let ([input (read-input)]) | |
(format #t "Part 1: ~a~%" (part1 input)) | |
(format #t "Part 2: ~a~%" (part2 input))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment