summaryrefslogtreecommitdiff
path: root/day09/day09.java
diff options
context:
space:
mode:
authorNat Lasseter <user@4574.co.uk>2023-12-10 17:50:56 +0000
committerNat Lasseter <user@4574.co.uk>2023-12-10 17:50:56 +0000
commit44d3c20b25b93b73374388a41b9282cb8e557cc2 (patch)
tree39f1a9b94939ebeb77bc3f912d9f6082b83bed62 /day09/day09.java
parent0c8aba4e6a6fc64bbd0452e82abd3582849ef2c3 (diff)
Day 09 part 1
Diffstat (limited to 'day09/day09.java')
-rw-r--r--day09/day09.java77
1 files changed, 77 insertions, 0 deletions
diff --git a/day09/day09.java b/day09/day09.java
new file mode 100644
index 0000000..4609508
--- /dev/null
+++ b/day09/day09.java
@@ -0,0 +1,77 @@
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.Arrays;
+import java.util.ArrayList;
+
+public class day09 {
+ public static void main(String args[]) throws IOException {
+ RandomAccessFile input = new RandomAccessFile("input", "r");
+ System.out.println("Day 09 Part 1: " + part1(input));
+ input.seek(0);
+ System.out.println("Day 09 Part 2: " + part2(input));
+ input.close();
+ }
+
+ public static String part1(RandomAccessFile input) throws IOException {
+ 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 += predictNext(nums);
+ }
+ return Integer.toString(sum);
+ }
+
+ public static String part2(RandomAccessFile input) throws IOException {
+ return "WIP";
+ }
+
+ private static int predictNext(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);
+ }
+
+ for (int i = differences.size() - 2; i >= 0; i--) {
+ ArrayList<Integer> lastrow = differences.get(i+1);
+ ArrayList<Integer> row = differences.get(i);
+ row.add(row.get(row.size() - 1) + lastrow.get(lastrow.size() - 1));
+ }
+
+ ArrayList<Integer> first = differences.get(0);
+ return first.get(first.size() - 1);
+ }
+
+ private static boolean allZero(ArrayList<Integer> list) {
+ for(int i: list) {
+ if (i != 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static ArrayList<Integer> getDifferences(ArrayList<Integer> last) {
+ ArrayList<Integer> next = new ArrayList<>();
+
+ for (int i = 1; i < last.size(); i++) {
+ next.add(last.get(i) - last.get(i-1));
+ }
+
+ return next;
+ }
+}