Skip to content

Commit cf87e70

Browse files
committed
2024 Day 2 cleanup
1 parent f01b123 commit cf87e70

File tree

1 file changed

+24
-12
lines changed
  • src/main/java/net/leibi/adventofcode2024/day2

1 file changed

+24
-12
lines changed

src/main/java/net/leibi/adventofcode2024/day2/Day2.java

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -30,30 +30,42 @@ boolean isSafe(List<Integer> report, boolean dampener) {
3030
final var failedIndices = getFailedIndices(report, direction);
3131
if (dampener && !failedIndices.isEmpty()) {
3232
for (var i = 0; i < report.size(); i++) {
33-
var clone = new ArrayList<>(report);
34-
clone.remove(i);
33+
final var clone = getReducedClone(report, i);
3534
if (isSafe(clone, false)) return true;
3635
}
3736
}
3837
return failedIndices.isEmpty();
3938
}
4039

40+
private static ArrayList<Integer> getReducedClone(List<Integer> report, int i) {
41+
var clone = new ArrayList<>(report);
42+
clone.remove(i);
43+
return clone;
44+
}
45+
4146
private static Set<Integer> getFailedIndices(List<Integer> report, Direction direction) {
4247
Set<Integer> failedIndices = new HashSet<>();
43-
for (var i = 1; i < report.size(); i++) {
44-
var diff = getDiff(report, i);
45-
if (isNotSafeDistance(diff)) {
46-
failedIndices.add(i - 1);
47-
}
48-
49-
Direction localDir = getDirection(diff);
50-
if (localDir != direction) {
51-
failedIndices.add(i - 1);
52-
}
48+
for (var index = 1; index < report.size(); index++) {
49+
var diff = getDiff(report, index);
50+
addToFailedIndicesIfUnsafeDistance(diff, failedIndices, index);
51+
addToFailedIndicesIfDirectionChanges(direction, diff, failedIndices, index);
5352
}
5453
return failedIndices;
5554
}
5655

56+
private static void addToFailedIndicesIfDirectionChanges(Direction direction, int diff, Set<Integer> failedIndices, int i) {
57+
Direction localDir = getDirection(diff);
58+
if (localDir != direction) {
59+
failedIndices.add(i - 1);
60+
}
61+
}
62+
63+
private static void addToFailedIndicesIfUnsafeDistance(int diff, Set<Integer> failedIndices, int i) {
64+
if (isNotSafeDistance(diff)) {
65+
failedIndices.add(i - 1);
66+
}
67+
}
68+
5769
private static int getDiff(List<Integer> report, int i) {
5870
return report.get(i) - report.get(i - 1);
5971
}

0 commit comments

Comments
 (0)