use reducers instead of foreach
This commit is contained in:
@@ -9,10 +9,9 @@ import java.util.Scanner;
|
||||
|
||||
public class Day04 {
|
||||
|
||||
private static int neighbors = 0;
|
||||
private static int score = 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) {
|
||||
Instant start = Instant.now();
|
||||
@@ -37,25 +36,20 @@ public class Day04 {
|
||||
for (int i = 0; i < size; i++) {
|
||||
String key = "%s-%s".formatted(i, rowIndex);
|
||||
if (row[i].equals("@")) {
|
||||
floor.put(key, true);
|
||||
} else {
|
||||
floor.put(key, false);
|
||||
floor.put(key, 1);
|
||||
}
|
||||
|
||||
}
|
||||
rowIndex++;
|
||||
}
|
||||
floor.forEach((key, value) -> {
|
||||
if (value) {
|
||||
if (value == 1) {
|
||||
String[] coords = key.split("-");
|
||||
int x = Integer.parseInt(coords[0]);
|
||||
int y = Integer.parseInt(coords[1]);
|
||||
neighbors = 0;
|
||||
generateNeighborKeys(x, y).forEach((coord) -> {
|
||||
if (floor.getOrDefault(coord, false)) {
|
||||
neighbors += 1;
|
||||
}
|
||||
});
|
||||
int neighbors = generateNeighborKeys(x, y).stream().reduce(
|
||||
0,
|
||||
(t, coord) -> (t + floor.getOrDefault(coord, 0)),
|
||||
Integer::sum);
|
||||
if (neighbors < 4) {
|
||||
score += 1;
|
||||
}
|
||||
@@ -79,30 +73,25 @@ public class Day04 {
|
||||
for (int i = 0; i < size; i++) {
|
||||
String key = "%s-%s".formatted(i, rowIndex);
|
||||
if (row[i].equals("@")) {
|
||||
floor.put(key, true);
|
||||
} else {
|
||||
floor.put(key, false);
|
||||
floor.put(key, 1);
|
||||
}
|
||||
|
||||
}
|
||||
rowIndex++;
|
||||
}
|
||||
while (true) {
|
||||
Map<String, Boolean> newFloor = new java.util.HashMap<>(floor);
|
||||
Map<String, Integer> newFloor = new java.util.HashMap<>(floor);
|
||||
floor.forEach((key, value) -> {
|
||||
if (value) {
|
||||
if (value == 1) {
|
||||
String[] coords = key.split("-");
|
||||
int x = Integer.parseInt(coords[0]);
|
||||
int y = Integer.parseInt(coords[1]);
|
||||
neighbors = 0;
|
||||
generateNeighborKeys(x, y).forEach((coord) -> {
|
||||
if (floor.getOrDefault(coord, false)) {
|
||||
neighbors += 1;
|
||||
}
|
||||
});
|
||||
int neighbors = generateNeighborKeys(x, y).stream().reduce(
|
||||
0,
|
||||
(t, coord) -> (t + floor.getOrDefault(coord, 0)),
|
||||
Integer::sum);
|
||||
if (neighbors < 4) {
|
||||
round += 1;
|
||||
newFloor.put(key, false);
|
||||
newFloor.put(key, 0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user