From b13e847401578abb66bb32e495db5518f3e5caf7 Mon Sep 17 00:00:00 2001 From: David Ashby Date: Thu, 4 Dec 2025 22:30:22 -0500 Subject: [PATCH] use reducers instead of foreach --- src/Day04.java | 41 +++++++++++++++-------------------------- 1 file changed, 15 insertions(+), 26 deletions(-) diff --git a/src/Day04.java b/src/Day04.java index 092f9e9..967d771 100644 --- a/src/Day04.java +++ b/src/Day04.java @@ -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 floor = new java.util.HashMap<>(); + private static Map 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 newFloor = new java.util.HashMap<>(floor); + Map 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); } } });