diff options
| author | Mistivia <i@mistivia.com> | 2024-02-14 18:51:22 +0800 |
|---|---|---|
| committer | Mistivia <i@mistivia.com> | 2024-02-14 18:51:22 +0800 |
| commit | 2cedcf3dfdf44863129c84a55218c265075fd229 (patch) | |
| tree | d8456f640288e0bfea86cf60b0bc4e38fe1dce5d /advent-of-code/2023/02/2.rkt | |
| parent | c3e3f8127767541a88c2c211878341f33c03f055 (diff) | |
refactor advent of code 2023 day 02 from c to racket
Diffstat (limited to 'advent-of-code/2023/02/2.rkt')
| -rw-r--r-- | advent-of-code/2023/02/2.rkt | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/advent-of-code/2023/02/2.rkt b/advent-of-code/2023/02/2.rkt new file mode 100644 index 0000000..8975a27 --- /dev/null +++ b/advent-of-code/2023/02/2.rkt @@ -0,0 +1,49 @@ +#lang racket + +(define fp (open-input-file "input")) + +(define (get-lines fp) + (let loop ((lines '())) + (define l (read-line fp)) + (if (eof-object? l) + (reverse lines) + (loop (cons l lines))))) + +(define lines (get-lines fp)) + +(define (extract-game line) + (define game-str (cadr (string-split line ":"))) + (define sets-str (string-split game-str ";")) + (set! sets-str (map string-trim sets-str)) + (map extract-set sets-str)) + +(define (extract-set str) + (define r 0) + (define g 0) + (define b 0) + (define balls (string-split str ",")) + (set! balls + (map (lambda (s) + (define pair (map string-trim (string-split s " "))) + (list (string->number (car pair)) (cadr pair))) + balls)) + (let loop ((balls balls)) + (if (null? balls) + '() + (let () + (define ball (car balls)) + (define number (car ball)) + (define color (cadr ball)) + (cond ((string=? "red" color) (set! r number)) + ((string=? "green" color) (set! g number)) + ((string=? "blue" color) (set! b number))) + (loop (cdr balls))))) + (list r g b)) + +(define (power game) + (define rs (map car game)) + (define gs (map cadr game)) + (define bs (map caddr game)) + (* (apply max rs) (apply max gs) (apply max bs))) + +(apply + (map power (map extract-game lines))) |
