2.rkt 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #lang racket
  2. (require "../lib/utils.rkt")
  3. (define fp (open-input-file "input"))
  4. (define lines (get-lines fp))
  5. (define (extract-game line)
  6. (define game-str (cadr (string-split line ":")))
  7. (define sets-str (string-split game-str ";"))
  8. (set! sets-str (map string-trim sets-str))
  9. (map extract-set sets-str))
  10. (define (extract-set str)
  11. (define r 0)
  12. (define g 0)
  13. (define b 0)
  14. (define balls (string-split str ","))
  15. (set! balls
  16. (map (λ (s)
  17. (define pair (map string-trim (string-split s " ")))
  18. (list (string->number (car pair)) (cadr pair)))
  19. balls))
  20. (let loop ((balls balls))
  21. (if (null? balls)
  22. '()
  23. (let ()
  24. (define ball (car balls))
  25. (define number (car ball))
  26. (define color (cadr ball))
  27. (cond ((string=? "red" color) (set! r number))
  28. ((string=? "green" color) (set! g number))
  29. ((string=? "blue" color) (set! b number)))
  30. (loop (cdr balls)))))
  31. (list r g b))
  32. (define (power game)
  33. (define rs (map car game))
  34. (define gs (map cadr game))
  35. (define bs (map caddr game))
  36. (* (apply max rs) (apply max gs) (apply max bs)))
  37. (apply + (map power (map extract-game lines)))