2.rkt 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #lang racket
  2. (require "../lib/utils.rkt")
  3. (define lines
  4. (call-with-input-file "input"
  5. (λ (fp) (get-lines fp))))
  6. (define patterns (split-list-by "" lines))
  7. (define (fix-smudge pattern x y)
  8. (define new-pattern (map string-copy pattern))
  9. (define pattern-vec (list->vector new-pattern))
  10. (define c (string-ref (vector-ref pattern-vec y) x))
  11. (case c
  12. ((#\#) (string-set! (vector-ref pattern-vec y) x #\.))
  13. ((#\.) (string-set! (vector-ref pattern-vec y) x #\#)))
  14. (vector->list pattern-vec))
  15. (define (find-reflection lines)
  16. (define lines-vec (list->vector lines))
  17. (define len (vector-length lines-vec))
  18. (define (find-first)
  19. (let loop ((i 0) (ret '()))
  20. (if (>= i (- len 1))
  21. (reverse ret)
  22. (if (string=? (vector-ref lines-vec i)
  23. (vector-ref lines-vec (+ i 1)))
  24. (loop (+ 1 i) (cons i ret))
  25. (loop (+ 1 i) ret)))))
  26. (define (count start)
  27. (let loop ((cnt 1) (i start))
  28. (if (or (< i 0)
  29. (>= (+ start cnt) len))
  30. (+ start 1)
  31. (if (string=? (vector-ref lines-vec i)
  32. (vector-ref lines-vec (+ start cnt)))
  33. (loop (+ 1 cnt) (- i 1))
  34. 0))))
  35. (define start (find-first))
  36. (if (null? start)
  37. '()
  38. (filter (λ (x) (not (= 0 x)))
  39. (map count start))))
  40. (define (score pattern)
  41. (define h-score (map (λ (x) (* 100 x))(find-reflection pattern)))
  42. (define w-score (find-reflection (transpose-list pattern)))
  43. (filter (λ (x) (not (= 0 x)))
  44. (append h-score w-score)))
  45. (define (fixed-score pattern)
  46. (define original-score (car (score pattern)))
  47. (define w (string-length (car pattern)))
  48. (define h (length pattern))
  49. (let loop ((x 0) (y 0))
  50. (if (>= y h)
  51. 0
  52. (if (>= x w)
  53. (loop 0 (+ 1 y))
  54. (let ()
  55. (define s (score (fix-smudge pattern x y)))
  56. (define result (filter (λ (x) (not (= original-score x)))
  57. s))
  58. (if (null? result)
  59. (loop (+ 1 x) y)
  60. (car result)))))))
  61. (apply + (map fixed-score patterns))