Browse Source

solve aoc 2023 09

Mistivia 1 year ago
parent
commit
97b449552b
3 changed files with 54 additions and 0 deletions
  1. 1 0
      advent-of-code/2023/.gitignore
  2. 27 0
      advent-of-code/2023/09/1.rkt
  3. 26 0
      advent-of-code/2023/09/2.rkt

+ 1 - 0
advent-of-code/2023/.gitignore

@@ -0,0 +1 @@
+input

+ 27 - 0
advent-of-code/2023/09/1.rkt

@@ -0,0 +1,27 @@
+#lang racket
+
+(require "../../lib/utils.rkt")
+
+(define lines
+  (call-with-input-file "input"
+    (λ (fp)
+      (get-lines fp))))
+
+(define (parse-data line)
+  (map string->number (string-split line)))
+
+(define data (map parse-data lines))
+
+(define (diff lst)
+  (let loop ((cur lst) (ret '()))
+    (if (or (null? cur) (null? (cdr cur)))
+      (reverse ret)
+      (loop (cdr cur) (cons (- (cadr cur) (car cur)) ret)))))
+
+(define (predict lst)
+  (if (andmap (λ (x) (= x (car lst))) lst)
+    (car lst)
+    (+ (last lst) (predict (diff lst)))))
+
+(apply + (map predict data))
+

+ 26 - 0
advent-of-code/2023/09/2.rkt

@@ -0,0 +1,26 @@
+#lang racket
+
+(require "../../lib/utils.rkt")
+
+(define lines
+  (call-with-input-file "input"
+    (λ (fp)
+      (get-lines fp))))
+
+(define (parse-data line)
+  (map string->number (string-split line)))
+
+(define data (map parse-data lines))
+
+(define (diff lst)
+  (let loop ((cur lst) (ret '()))
+    (if (or (null? cur) (null? (cdr cur)))
+      (reverse ret)
+      (loop (cdr cur) (cons (- (cadr cur) (car cur)) ret)))))
+
+(define (predict lst)
+  (if (andmap (λ (x) (= x (car lst))) lst)
+    (car lst)
+    (- (car lst) (predict (diff lst)))))
+
+(apply + (map predict data))