|
4 | 4 | import java.util.List;
|
5 | 5 |
|
6 | 6 | 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) { |
13 | 7 |
|
14 |
| - int minSafe = 1; |
15 |
| - int maxSafe = 3; |
| 8 | + public static final int MIN_SAFE = 1; |
| 9 | + public static final int MAX_SAFE = 3; |
16 | 10 |
|
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(); |
22 | 13 |
|
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 | + } |
28 | 20 | }
|
| 21 | + return cnt; |
| 22 | + } |
29 | 23 |
|
30 |
| - enum Direction { |
31 |
| - INC, |
32 |
| - DEC, |
33 |
| - BOTH |
34 |
| - } |
| 24 | + boolean isSafe(List<Integer> report) { |
35 | 25 |
|
| 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 | + } |
36 | 55 | }
|
0 commit comments