-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPartTwo.java
122 lines (104 loc) · 4.63 KB
/
PartTwo.java
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
/**
* --- Day 3: Gear Ratios --- --- Part Two ---
*
*
* https://adventofcode.com/2023/day/3
**/
public class PartTwo {
public static void main(String[] args) throws Exception {
int total = 0;
int height = 140;
int width = 140;
String grid[][] = new String[height][width];
HashSet<int[]> numbersStartAt = new HashSet<>();
try {
Scanner scanner = new Scanner(new File("./src/input.txt"));
int hIndex = 0;
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
grid[hIndex] = input.split("");
hIndex++;
}
scanner.close();
for (int h = 0; h < grid.length; h++) {
String[] row = grid[h];
for (int j = 0; j < row.length; j++) {
String value = row[j];
Character c = value.charAt(0);
numbersStartAt = new HashSet<>();
if (c.equals('*')) {
// Lines below and above
int hAbove = h - 1;
int hBelow = h + 1;
for (int line = hAbove; line <= hBelow; line++) {
// Row to the left and right
int rLeft = j - 1;
int rRight = j + 1;
for (int index = rLeft; index <= rRight; index++) {
if (index < 0 || index >= row.length
|| line < 0 || line >= grid.length
|| !Character.isDigit(
grid[line][index]
.charAt(0))) {
continue;
}
int column = index;
while (column >= 0
&& Character.isDigit(
grid[line][column]
.charAt(0))) {
column -= 1;
}
int[] pair = new int[] { line, column + 1 };
boolean alreadyExists = false;
for (int[] p : numbersStartAt) {
if (p[0] == pair[0] && p[1] == pair[1]) {
alreadyExists = true;
continue;
}
}
if (!alreadyExists) {
numbersStartAt.add(pair);
}
}
if (numbersStartAt.size() != 2) {
continue;
}
String[] gearPair = new String[2];
for (int[] pair : numbersStartAt) {
int pH = pair[0];
int pR = pair[1];
String[] pRow = grid[pH];
String pValue = "";
int index = pR;
while (index < pRow.length
&& Character.isDigit(
pRow[index].charAt(0))) {
pValue += pRow[index];
index += 1;
}
if (gearPair[0] == null) {
gearPair[0] = pValue;
} else {
gearPair[1] = pValue;
total += Integer.parseInt(
gearPair[0]) *
Integer.parseInt(gearPair[1]);
gearPair = new String[2];
numbersStartAt = new HashSet<>();
}
}
}
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
System.out.println(total);
}
}