-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathDay18.java
66 lines (54 loc) · 1.8 KB
/
Day18.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
package com.sbaars.adventofcode.year16.days;
import com.sbaars.adventofcode.year16.Day2016;
public class Day18 extends Day2016 {
private static final int ROWS_PART1 = 40;
private static final int ROWS_PART2 = 400000;
private static final char TRAP = '^';
private static final char SAFE = '.';
public Day18() {
super(18);
}
public static void main(String[] args) {
new Day18().printParts();
}
private boolean isTrap(char left, char center, char right) {
return (left == TRAP && center == TRAP && right == SAFE) ||
(center == TRAP && right == TRAP && left == SAFE) ||
(left == TRAP && center == SAFE && right == SAFE) ||
(right == TRAP && center == SAFE && left == SAFE);
}
private String generateNextRow(String currentRow) {
StringBuilder nextRow = new StringBuilder();
for (int i = 0; i < currentRow.length(); i++) {
char left = i > 0 ? currentRow.charAt(i - 1) : SAFE;
char center = currentRow.charAt(i);
char right = i < currentRow.length() - 1 ? currentRow.charAt(i + 1) : SAFE;
nextRow.append(isTrap(left, center, right) ? TRAP : SAFE);
}
return nextRow.toString();
}
private int countSafeTiles(String firstRow, int rows) {
String currentRow = firstRow;
int safeTiles = countSafeInRow(currentRow);
for (int i = 1; i < rows; i++) {
currentRow = generateNextRow(currentRow);
safeTiles += countSafeInRow(currentRow);
}
return safeTiles;
}
private int countSafeInRow(String row) {
int count = 0;
for (char c : row.toCharArray()) {
if (c == SAFE) count++;
}
return count;
}
@Override
public Object part1() {
return countSafeTiles(day().trim(), ROWS_PART1);
}
@Override
public Object part2() {
return countSafeTiles(day().trim(), ROWS_PART2);
}
}