use reducers instead of foreach

This commit is contained in:
2025-12-04 22:30:22 -05:00
parent 1aeeaa780e
commit b13e847401

View File

@@ -9,10 +9,9 @@ import java.util.Scanner;
public class Day04 { public class Day04 {
private static int neighbors = 0;
private static int score = 0; private static int score = 0;
private static int round = 0; private static int round = 0;
private static Map<String, Boolean> floor = new java.util.HashMap<>(); private static Map<String, Integer> floor = new java.util.HashMap<>();
public static void main(String[] args) { public static void main(String[] args) {
Instant start = Instant.now(); Instant start = Instant.now();
@@ -37,25 +36,20 @@ public class Day04 {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
String key = "%s-%s".formatted(i, rowIndex); String key = "%s-%s".formatted(i, rowIndex);
if (row[i].equals("@")) { if (row[i].equals("@")) {
floor.put(key, true); floor.put(key, 1);
} else {
floor.put(key, false);
} }
} }
rowIndex++; rowIndex++;
} }
floor.forEach((key, value) -> { floor.forEach((key, value) -> {
if (value) { if (value == 1) {
String[] coords = key.split("-"); String[] coords = key.split("-");
int x = Integer.parseInt(coords[0]); int x = Integer.parseInt(coords[0]);
int y = Integer.parseInt(coords[1]); int y = Integer.parseInt(coords[1]);
neighbors = 0; int neighbors = generateNeighborKeys(x, y).stream().reduce(
generateNeighborKeys(x, y).forEach((coord) -> { 0,
if (floor.getOrDefault(coord, false)) { (t, coord) -> (t + floor.getOrDefault(coord, 0)),
neighbors += 1; Integer::sum);
}
});
if (neighbors < 4) { if (neighbors < 4) {
score += 1; score += 1;
} }
@@ -79,30 +73,25 @@ public class Day04 {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
String key = "%s-%s".formatted(i, rowIndex); String key = "%s-%s".formatted(i, rowIndex);
if (row[i].equals("@")) { if (row[i].equals("@")) {
floor.put(key, true); floor.put(key, 1);
} else {
floor.put(key, false);
} }
} }
rowIndex++; rowIndex++;
} }
while (true) { while (true) {
Map<String, Boolean> newFloor = new java.util.HashMap<>(floor); Map<String, Integer> newFloor = new java.util.HashMap<>(floor);
floor.forEach((key, value) -> { floor.forEach((key, value) -> {
if (value) { if (value == 1) {
String[] coords = key.split("-"); String[] coords = key.split("-");
int x = Integer.parseInt(coords[0]); int x = Integer.parseInt(coords[0]);
int y = Integer.parseInt(coords[1]); int y = Integer.parseInt(coords[1]);
neighbors = 0; int neighbors = generateNeighborKeys(x, y).stream().reduce(
generateNeighborKeys(x, y).forEach((coord) -> { 0,
if (floor.getOrDefault(coord, false)) { (t, coord) -> (t + floor.getOrDefault(coord, 0)),
neighbors += 1; Integer::sum);
}
});
if (neighbors < 4) { if (neighbors < 4) {
round += 1; round += 1;
newFloor.put(key, false); newFloor.put(key, 0);
} }
} }
}); });