Created
December 7, 2023 12:19
-
-
Save qookei/1b5321896a68bd0fb44646f6fcd820fe 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 (ice-9 textual-ports) (srfi srfi-1) (ice-9 match) (ice-9 format)) | |
(define (hand-str str) | |
(string-map | |
(λ (chr) | |
(integer->char (+ (char->integer #\a) | |
(string-index "23456789TJQKA" chr)))) | |
str)) | |
(define (process-line line) | |
(let ([parts (string-split line #\space)]) | |
(cons (hand-str (car parts)) | |
(string->number (cadr parts))))) | |
(define (read-input) | |
(let ([line (get-line (current-input-port))]) | |
(if (eof-object? line) | |
'() | |
(cons (process-line line) | |
(read-input))))) | |
(define (hand-type hand) | |
(match (sort (string->list hand) char<?) | |
;; 5-of-a-kind | |
[(a a a a a) 7] | |
;; 4-of-a-kind | |
[(a a a a b) 6] | |
[(b a a a a) 6] | |
;; Full house | |
[(a a a b b) 5] | |
[(b b a a a) 5] | |
;; 3-of-a-kind | |
[(a a a b c) 4] | |
[(b a a a c) 4] | |
[(b c a a a) 4] | |
;; Two pair | |
[(a a b b c) 3] | |
[(c a a b b) 3] | |
[(a a c b b) 3] | |
;; One pair | |
[(a a b c d) 2] | |
[(b a a c d) 2] | |
[(b c a a d) 2] | |
[(b c d a a) 2] | |
;; All different | |
[(a b c d e) 1])) | |
(define (hand<? hand-type left right) | |
(let ([left-type (hand-type left)] | |
[right-type (hand-type right)]) | |
(if (equal? left-type right-type) | |
(string< left right) | |
(< left-type right-type)))) | |
(define (string-replace-char str what with) | |
(string-map (λ (chr) | |
(if (char=? chr what) | |
with | |
chr)) | |
str)) | |
(define (diminish-jokers hand+bet) | |
(cons (string-replace-char (car hand+bet) #\j #\space) | |
(cdr hand+bet))) | |
(define (joker-hand-type hand) | |
(apply max (map (λ (i) | |
(hand-type | |
(string-replace-char | |
hand | |
#\space | |
(integer->char (+ i (char->integer #\a)))))) | |
(iota 13)))) | |
(define (part-common hand-type input) | |
(let ([ordered (sort input | |
(λ (left right) | |
(hand<? hand-type | |
(car left) | |
(car right))))]) | |
(fold + 0 | |
(map (λ (hand+bet index) | |
(* (cdr hand+bet) index)) | |
ordered | |
(iota (length ordered) 1))))) | |
(let ([input (read-input)]) | |
(format #t "Part 1: ~a~%" (part-common hand-type input)) | |
(format #t "Part 2: ~a~%" (part-common joker-hand-type (map diminish-jokers input)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment