summaryrefslogtreecommitdiff
path: root/day11/day11.java
blob: 6bf7c19b4dfdca05908158b03cab70c85df9c1da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;

public class day11 {
  public static void main(String args[]) throws IOException {
    RandomAccessFile input = new RandomAccessFile("input", "r");
    System.out.println("Day 11 Part 1: " + part1(input));
    input.seek(0);
    System.out.println("Day 11 Part 2: " + part2(input));
    input.close();
  }

  public static String part1(RandomAccessFile input) throws IOException {
    ArrayList<ArrayList<Pixel>> image = new ArrayList<>();

    String line;
    while ((line = input.readLine()) != null) {
      ArrayList<Pixel> linea = new ArrayList<>();
      for (char ch: line.toCharArray()) {
        if (ch == '.') {
          linea.add(Pixel.Space);
        } else if (ch == '#') {
          linea.add(Pixel.Galaxy);
        }
      }
      image.add(linea);
    }

    for (int i = image.size() - 1; i >= 0; i--) {
      if (allSpace(image.get(i))) {
        image.add(i+1, (ArrayList<Pixel>) image.get(i).clone());
      }
    }

    for (int i = image.get(0).size() - 1; i >= 0; i--) {
      ArrayList<Pixel> col = new ArrayList<>();

      for (ArrayList<Pixel> row: image) {
        col.add(row.get(i));
      }

      if (allSpace(col)) {
        for (ArrayList<Pixel> row: image) {
          row.add(i+1, row.get(i));
        }
      }
    }

    ArrayList<Integer[]> galaxies = new ArrayList<>();
    for (int r = 0; r < image.size(); r++) {
      for (int c = 0; c < image.get(0).size(); c++) {
        if (image.get(r).get(c) == Pixel.Galaxy) {
          galaxies.add(new Integer[] {r, c});
        }
      }
    }

    int sum = 0;

    for (int i = 0; i < galaxies.size() - 1; i++) {
      for (int j = i + 1; j < galaxies.size(); j++) {
        sum += dist(galaxies.get(i), galaxies.get(j));
      }
    }

    return Integer.toString(sum);
  }

  public static String part2(RandomAccessFile input) throws IOException {
    return "WIP";
  }

  static enum Pixel {
    Space,
    Galaxy
  }

  private static boolean allSpace(ArrayList<Pixel> line) {
    for (Pixel px: line) {
      if (px == Pixel.Galaxy) {
        return false;
      }
    }
    return true;
  }

  private static int dist(Integer[] i, Integer[] j) {
    return Math.abs(i[0] - j[0]) + Math.abs(i[1] - j[1]);
  }
}