Skip to content

Commit ddb3e22

Browse files
committed
feat: 2024 day2 part 1
1 parent dcecd1a commit ddb3e22

File tree

3 files changed

+1050
-23
lines changed

3 files changed

+1050
-23
lines changed

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

Lines changed: 42 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,52 @@
44
import java.util.List;
55

66
public class Day2 {
7-
public long part1(String input) {
8-
final var list = input.lines().map(s -> s.split("\\s+")).toList();
9-
return list.stream().filter(a -> isSafe(Arrays.asList(a))).count();
10-
}
11-
12-
boolean isSafe(List<Integer> report) {
137

14-
int minSafe = 1;
15-
int maxSafe = 3;
8+
public static final int MIN_SAFE = 1;
9+
public static final int MAX_SAFE = 3;
1610

17-
Direction direction = report.get(1) - report.get(0) > 0 ? Direction.INC : Direction.DEC;
18-
for (var i = 1; i < report.size(); i++) {
19-
var diff = report.get(i) - report.get(i - 1);
20-
if (Math.abs(diff) > maxSafe || Math.abs(diff) < minSafe)
21-
return false;
11+
public long part1(String input) {
12+
final var list = input.lines().map(s -> s.split("\\s+")).toList();
2213

23-
Direction localDir = diff > 0 ? Direction.INC : Direction.DEC;
24-
if (localDir != direction)
25-
return false;
26-
}
27-
return true;
14+
long cnt = 0;
15+
for (String[] strings : list) {
16+
var integerList = Arrays.stream(strings).map(Integer::parseInt).toList();
17+
if (isSafe(integerList)) {
18+
cnt++;
19+
}
2820
}
21+
return cnt;
22+
}
2923

30-
enum Direction {
31-
INC,
32-
DEC,
33-
BOTH
34-
}
24+
boolean isSafe(List<Integer> report) {
3525

26+
Direction direction = getDirection(getDiff(report, 1));
27+
boolean returnValue = true;
28+
for (var i = 1; i < report.size(); i++) {
29+
var diff = getDiff(report, i);
30+
if (isNotSafeDistance(diff)) return false;
31+
32+
Direction localDir = getDirection(diff);
33+
if (localDir != direction) return false;
34+
}
35+
return returnValue;
36+
}
37+
38+
private static int getDiff(List<Integer> report, int i) {
39+
return report.get(i) - report.get(i - 1);
40+
}
41+
42+
private static Direction getDirection(int diff) {
43+
return diff > 0 ? Direction.INC : Direction.DEC;
44+
}
45+
46+
private static boolean isNotSafeDistance(int diff) {
47+
return Math.abs(diff) > MAX_SAFE || Math.abs(diff) < MIN_SAFE;
48+
}
49+
50+
enum Direction {
51+
INC,
52+
DEC,
53+
BOTH
54+
}
3655
}

0 commit comments

Comments
 (0)