Skip to content

Commit 7ab839e

Browse files
committed
refactor: generalize day 4 part 1 solution
1 parent 64f0faa commit 7ab839e

File tree

1 file changed

+6
-29
lines changed

1 file changed

+6
-29
lines changed

src/main/java/com/adventofcode/flashk/day04/CeresSearch.java

Lines changed: 6 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -40,47 +40,24 @@ public CeresSearch(char[][] input){
4040
}
4141

4242
public long solveA() {
43-
long totalCount = countHorizontal();
44-
totalCount += countVertical();
45-
totalCount += countDiagonal();
46-
return totalCount;
43+
return xPositions.stream().map(this::find).reduce(0, Integer::sum);
4744
}
4845

4946
public long solveB() {
5047
return aPositions.stream().filter(this::hasMasDiagonal1).filter(this::hasMasDiagonal2).count();
5148
}
5249

53-
private int countHorizontal() {
54-
int totalCount = 0;
55-
for(int row = 0; row < rows; row++) {
56-
String line = new String(input[row]);
57-
totalCount += StringUtils.countMatches(line, XMAS) + StringUtils.countMatches(line, SAMX);
58-
}
59-
return totalCount;
60-
}
61-
62-
private int countVertical() {
63-
64-
char[][] transposedInput = Array2DUtil.transpose(input);
65-
int totalCount = 0;
66-
for(int row = 0; row < rows; row++) {
67-
String line = new String(transposedInput[row]);
68-
totalCount += StringUtils.countMatches(line, XMAS) + StringUtils.countMatches(line, SAMX);
69-
}
70-
return totalCount;
71-
}
72-
73-
private long countDiagonal() {
74-
return xPositions.stream().map(this::find).reduce(0, Integer::sum);
75-
}
76-
7750
private int find(Vector2 xPos) {
7851
char[] word = MAS.toCharArray();
7952

8053
int totalCount = find(word, 0, xPos, new Vector2(-1,-1));
8154
totalCount += find(word, 0, xPos, new Vector2(-1,1));
8255
totalCount += find(word, 0, xPos, new Vector2(1,-1));
8356
totalCount += find(word, 0, xPos, new Vector2(1,1));
57+
totalCount += find(word, 0, xPos, new Vector2(-1,0));
58+
totalCount += find(word, 0, xPos, new Vector2(1,0));
59+
totalCount += find(word, 0, xPos, new Vector2(0,-1));
60+
totalCount += find(word, 0, xPos, new Vector2(0,1));
8461

8562
return totalCount;
8663
}
@@ -153,4 +130,4 @@ private boolean isOutOfRange(int row, int col) {
153130
return row < 0 || row >= rows || col < 0 || col >= cols;
154131
}
155132

156-
}
133+
}

0 commit comments

Comments
 (0)