diff options
author | Nat Lasseter <user@4574.co.uk> | 2023-12-12 01:05:41 +0000 |
---|---|---|
committer | Nat Lasseter <user@4574.co.uk> | 2023-12-12 01:05:41 +0000 |
commit | a09db7c49822168c90c5c48477e434f32d7bf9ba (patch) | |
tree | 1988845d16a974ab633d5fbfbb7d94c3d79bb4b5 /day11 | |
parent | 0cecba62086661c79900f4a70b5549885ffd2c59 (diff) |
Day 11 part 2
Diffstat (limited to 'day11')
-rw-r--r-- | day11/day11.java | 76 |
1 files changed, 75 insertions, 1 deletions
diff --git a/day11/day11.java b/day11/day11.java index 6bf7c19..2fd9f8a 100644 --- a/day11/day11.java +++ b/day11/day11.java @@ -68,7 +68,43 @@ public class day11 { } public static String part2(RandomAccessFile input) throws IOException { - return "WIP"; + ArrayList<Integer[]> galaxies = new ArrayList<>(); + + String line; + int h = 0; + int w = 0; + while ((line = input.readLine()) != null) { + w = 0; + for (char ch: line.toCharArray()) { + if (ch == '#') { + galaxies.add(new Integer[] {h, w}); + } + w += 1; + } + h += 1; + } + + for (int r = h - 1; r >= 0; r--) { + if (rowEmpty(galaxies, r)) { + moveDown(galaxies, r, 999999); + } + } + + for (int c = w - 1; c >= 0; c--) { + if (colEmpty(galaxies, c)) { + moveRight(galaxies, c, 999999); + } + } + + long sum = 0; + + for (int i = 0; i < galaxies.size() - 1; i++) { + for (int j = i + 1; j < galaxies.size(); j++) { + sum += longDist(galaxies.get(i), galaxies.get(j)); + } + } + + return Long.toString(sum); } static enum Pixel { @@ -88,4 +124,42 @@ public class day11 { private static int dist(Integer[] i, Integer[] j) { return Math.abs(i[0] - j[0]) + Math.abs(i[1] - j[1]); } + + private static long longDist(Integer[] i, Integer[] j) { + return Math.abs(i[0] - j[0]) + Math.abs(i[1] - j[1]); + } + + private static boolean rowEmpty(ArrayList<Integer[]> galaxies, int row) { + for (Integer[] galaxy: galaxies) { + if (galaxy[0] == row) { + return false; + } + } + return true; + } + + private static void moveDown(ArrayList<Integer[]> galaxies, int row, int dist) { + for (Integer[] galaxy: galaxies) { + if (galaxy[0] > row) { + galaxy[0] += dist; + } + } + } + + private static boolean colEmpty(ArrayList<Integer[]> galaxies, int col) { + for (Integer[] galaxy: galaxies) { + if (galaxy[1] == col) { + return false; + } + } + return true; + } + + private static void moveRight(ArrayList<Integer[]> galaxies, int col, int dist) { + for (Integer[] galaxy: galaxies) { + if (galaxy[1] > col) { + galaxy[1] += dist; + } + } + } } |