-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPuzzle4.java
102 lines (94 loc) · 2.82 KB
/
Puzzle4.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
package advent2024;
import static java.lang.Math.incrementExact;
import adventlib.CharGrid;
import adventlib.CharGrid.Coord;
import adventlib.Dir;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.CharStreams;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* @author Éamonn McManus
*/
public class Puzzle4 {
private static final String SAMPLE =
"""
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
""";
private static final Map<String, Callable<Reader>> INPUT_PRODUCERS =
ImmutableMap.of(
"sample",
() -> new StringReader(SAMPLE),
"problem",
() -> new InputStreamReader(Puzzle4.class.getResourceAsStream("puzzle4.txt")));
public static void main(String[] args) throws Exception {
for (var entry : INPUT_PRODUCERS.entrySet()) {
String name = entry.getKey();
try (Reader r = entry.getValue().call()) {
List<String> lines = CharStreams.readLines(r);
CharGrid grid = new CharGrid(lines);
System.out.println("Part 1 count for " + name + " is " + countMatches1(grid));
System.out.println("Part 2 count for " + name + " is " + countMatches2(grid));
}
}
}
private static int countMatches1(CharGrid grid) {
int count = 0;
EnumSet<Dir> allDirs = EnumSet.allOf(Dir.class);
for (int line = 0; line < grid.height(); line++) {
for (int col = 0; col < grid.width(); col++) {
Coord coord = new Coord(line, col);
for (Dir dir : allDirs) {
boolean match = true;
for (int i = 0; i < 4; i++) {
char c = grid.get(dir.move(coord, i));
if (c != "XMAS".charAt(i)) {
match = false;
break;
}
}
if (match) {
count = incrementExact(count);
}
}
}
}
return count;
}
private static int countMatches2(CharGrid grid) {
var ms = ImmutableSet.of('M', 'S');
int count = 0;
for (int line = 1; line < grid.height() - 1; line++) {
for (int col = 1; col < grid.width() - 1; col++) {
if (grid.get(line, col) != 'A') {
continue;
}
var set1 = ImmutableSet.of(grid.get(line - 1, col - 1), grid.get(line + 1, col + 1));
if (!set1.equals(ms)) {
continue;
}
var set2 = ImmutableSet.of(grid.get(line - 1, col + 1), grid.get(line + 1, col - 1));
if (!set2.equals(ms)) {
continue;
}
count = incrementExact(count);
}
}
return count;
}
}