puzzle-02.scm 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. (import
  2. (except (rnrs base) let-values map error)
  3. (only (guile)
  4. lambda* λ
  5. command-line
  6. make-typed-array)
  7. (srfi srfi-1)
  8. (fileio))
  9. (define println
  10. (λ (thing)
  11. (simple-format (current-output-port) "~a\n" thing)))
  12. (define lines->landscape
  13. (λ (lines)
  14. (list->array 2 (map string->list lines))))
  15. (define count-trees
  16. (lambda* (landscape #:key (rows-step 1) (cols-step 1))
  17. (let* ([dim (array-dimensions landscape)]
  18. [height (first dim)]
  19. [width (second dim)])
  20. (let next-step ([cur-row-ind 0]
  21. [cur-col-ind 0]
  22. [encountered-trees 0])
  23. (cond
  24. [(>= cur-row-ind height) encountered-trees]
  25. [(char=? (array-ref landscape cur-row-ind cur-col-ind) #\#)
  26. (next-step (+ cur-row-ind rows-step)
  27. (remainder (+ cur-col-ind cols-step) width)
  28. (+ encountered-trees 1))]
  29. [else
  30. (next-step (+ cur-row-ind rows-step)
  31. (remainder (+ cur-col-ind cols-step) width)
  32. encountered-trees)])))))
  33. (define main
  34. (λ (cmd-line-args)
  35. (let* ([lines (get-lines-from-file (second cmd-line-args))]
  36. [landscape (lines->landscape lines)])
  37. (apply *
  38. (map (λ (step-pair)
  39. (count-trees landscape
  40. #:rows-step (car step-pair)
  41. #:cols-step (cdr step-pair)))
  42. '((1 . 1)
  43. (1 . 3)
  44. (1 . 5)
  45. (1 . 7)
  46. (2 . 1)))))))
  47. (simple-format (current-output-port)
  48. "~a\n"
  49. (main (command-line)))