From 69e43f1bf8bf1abad6f848a46cf40fe4e11c1598 Mon Sep 17 00:00:00 2001
From: Nat Lasseter <user@4574.co.uk>
Date: Sun, 10 Dec 2023 18:01:02 +0000
Subject: Day 09

---
 day09/day09.java | 37 ++++++++++++++++++++++++++++++++++++-
 1 file changed, 36 insertions(+), 1 deletion(-)

diff --git a/day09/day09.java b/day09/day09.java
index 4609508..15354cd 100644
--- a/day09/day09.java
+++ b/day09/day09.java
@@ -28,7 +28,18 @@ public class day09 {
   }
 
   public static String part2(RandomAccessFile input) throws IOException {
-    return "WIP";
+    String line;
+    int sum = 0;
+    while ((line = input.readLine()) != null) {
+      String[] linea = line.split(" ");
+      int[] nums = new int[linea.length];
+      for (int i = 0; i < linea.length; i++) {
+        nums[i] = Integer.parseInt(linea[i]);
+      }
+
+      sum += predictPre(nums);
+    }
+    return Integer.toString(sum);
   }
 
   private static int predictNext(int[] line) {
@@ -56,6 +67,30 @@ public class day09 {
     return first.get(first.size() - 1);
   }
 
+  private static int predictPre(int[] line) {
+    ArrayList<ArrayList<Integer>> differences = new ArrayList<>();
+    ArrayList<Integer> lastDiffs = new ArrayList<>();
+
+    for (int i: line) {
+      lastDiffs.add(i);
+    }
+
+    differences.add(lastDiffs);
+
+    while (!allZero(lastDiffs)) {
+      lastDiffs = getDifferences(lastDiffs);
+      differences.add(lastDiffs);
+    }
+
+    int temp = 0;
+    for (int i = differences.size() - 2; i >= 0; i--) {
+      ArrayList<Integer> row = differences.get(i);
+      temp = row.get(0) - temp;
+    }
+
+    return temp;
+  }
+
   private static boolean allZero(ArrayList<Integer> list) {
     for(int i: list) {
       if (i != 0) {
-- 
cgit v1.2.3