Browse Source

solve day 13 part 1

Mistivia 1 year ago
parent
commit
e28258fddc
2 changed files with 53 additions and 1 deletions
  1. 40 0
      13/1.rkt
  2. 13 1
      lib/utils.rkt

+ 40 - 0
13/1.rkt

@@ -0,0 +1,40 @@
+#lang racket
+
+(require "../lib/utils.rkt")
+
+(define lines
+  (call-with-input-file "input"
+    (λ (fp) (get-lines fp))))
+
+(define patterns (split-list-by "" lines))
+
+(define (find-reflection lines)
+  (define lines-vec (list->vector lines))
+  (define len (vector-length lines-vec))
+  (define (find-first)
+    (let loop ((i 0) (ret '()))
+      (if (>= i (- len 1))
+          (reverse ret)
+          (if (string=? (vector-ref lines-vec i)
+                        (vector-ref lines-vec (+ i 1)))
+              (loop (+ 1 i) (cons i ret))
+              (loop (+ 1 i) ret)))))
+  (define (count start)
+    (let loop ((cnt 1) (i start))
+      (if (or (< i 0)
+              (>= (+ start cnt) len))
+          (+ start 1)
+          (if (string=? (vector-ref lines-vec i)
+                        (vector-ref lines-vec (+ start cnt)))
+              (loop (+ 1 cnt) (- i 1))
+              0))))
+  (define start (find-first))
+  (if (null? start)
+      0
+      (apply max (map count start))))
+
+(define (score pattern)
+  (+ (* 100 (find-reflection pattern))
+     (find-reflection (transpose-list pattern))))
+
+(apply + (map score patterns))

+ 13 - 1
lib/utils.rkt

@@ -3,7 +3,8 @@
 (provide get-lines
 (provide get-lines
          enumerate
          enumerate
          repeat
          repeat
-         split-list-by)
+         split-list-by
+         transpose-list)
 
 
 (define (repeat n e)
 (define (repeat n e)
   (let loop ((i 0) (ret '()))
   (let loop ((i 0) (ret '()))
@@ -41,3 +42,14 @@
         (if (cmp e (car lst))
         (if (cmp e (car lst))
             (loop (cons (reverse cur) ret) '() (cdr lst))
             (loop (cons (reverse cur) ret) '() (cdr lst))
             (loop ret (cons (car lst) cur) (cdr lst))))))
             (loop ret (cons (car lst) cur) (cdr lst))))))
+
+(define (transpose-list lines)
+  (define width (string-length (car lines)))
+  (define new-lines (make-vector width))
+  (let loop ((i 0))
+    (if (>= i width)
+      (vector->list new-lines)
+      (let ()
+        (define char-list (map (λ (l) (string-ref l i)) lines))
+        (vector-set! new-lines i (list->string char-list))
+        (loop (+ i 1))))))