1.rkt 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 (possible? game)
  33. (if (null? game)
  34. #t
  35. (let ()
  36. (define head (car game))
  37. (if (or (> (car head) 12) ; r
  38. (> (cadr head) 13) ; g
  39. (> (caddr head) 14)) ; b
  40. #f
  41. (possible? (cdr game))))))
  42. (apply + (map cadr
  43. (filter (λ (game)
  44. (possible? (car game)))
  45. (enumerate (map extract-game lines)))))