puzzle-01.scm 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. (import
  2. (except (rnrs base) let-values map error)
  3. (only (guile) lambda* λ command-line string-null?)
  4. (srfi srfi-1)
  5. (ice-9 peg)
  6. (fileio)
  7. (display-utils)
  8. (prefix (peg-tree-utils) peg-tree:))
  9. ;; muted gold bags contain 1 wavy red bag, 3 mirrored violet bags, 5 bright gold bags, 5 plaid white bags.
  10. (define-peg-pattern SPACE none " ")
  11. (define-peg-pattern RULE-END none ".")
  12. (define-peg-pattern CONTAINMENT-SEPARATOR none ",")
  13. (define-peg-pattern NUMBER body (* (range #\0 #\9)))
  14. (define-peg-pattern WORD body (+ (range #\a #\z)))
  15. (define-peg-pattern SINGULAR-OR-PLURAL-BAG none (or "bags" "bag"))
  16. (define-peg-pattern NO-BAG none "no other bags")
  17. (define-peg-pattern COUNT all NUMBER)
  18. (define-peg-pattern COLOR-MOD all WORD)
  19. (define-peg-pattern COLOR all WORD)
  20. (define-peg-pattern CONTAINER all (and COLOR-MOD SPACE COLOR))
  21. (define-peg-pattern CONTAINMENT-POSSIBILITY all
  22. (and COUNT SPACE
  23. COLOR-MOD SPACE
  24. COLOR SPACE
  25. SINGULAR-OR-PLURAL-BAG))
  26. (define-peg-pattern CONTAINMENTS all
  27. (or (and (* (and CONTAINMENT-POSSIBILITY CONTAINMENT-SEPARATOR SPACE))
  28. (and CONTAINMENT-POSSIBILITY RULE-END))
  29. NO-BAG RULE-END))
  30. (define-peg-pattern RULE all
  31. (and CONTAINER SPACE
  32. "bags" SPACE
  33. "contain" SPACE
  34. CONTAINMENTS))
  35. (define main
  36. (λ (cmd-line-args)
  37. (let* ([lines (get-lines-from-file (second cmd-line-args))]
  38. [rules (map (λ (line) (match-pattern RULE line)) lines)])
  39. (peg-tree:find-in-tree* (peg:tree (fourth rules))
  40. (λ (sym) (symbol=? sym 'CONTAINMENT-POSSIBILITY))))))
  41. ;; (display-list (main (command-line)))
  42. (simple-format (current-output-port) "~a\n" (main (command-line)))