-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay2Part2.java
More file actions
71 lines (56 loc) · 2.26 KB
/
Copy pathDay2Part2.java
File metadata and controls
71 lines (56 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.function.BiFunction;
public class Day2Part2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("day2-input.txt"));
int totalSafeReports = 0;
while (input.hasNextLine()) {
String[] numbers = input.nextLine().split(" ");
int[] levels = Arrays.stream(numbers).mapToInt(Integer::parseInt).toArray();
if (isSafeReport(levels)) {
totalSafeReports++;
} else {
// It really don't like the way, but it is straightforward and possible for levels < 10 and 1000 reports
for (int i = 0; i < levels.length; i++) {
if (isSafeReport(truncate(levels, i))) {
totalSafeReports++;
break;
}
}
}
}
System.out.println(totalSafeReports);
}
private static int[] truncate(int[] levels, int excludeIdx) {
int[] truncatedReport = new int[levels.length - 1];
int truncatedIdx = 0;
for (int i = 0; i < levels.length; i++) {
if (i != excludeIdx) {
truncatedReport[truncatedIdx++] = levels[i];
}
}
return truncatedReport;
}
public static boolean isSafeReport(int[] levels) {
// Assumes that levels count > 1
boolean isAscending = levels[0] < levels[1];
// We don't want to check isAscending everytime, so let's introduce the diff's lambda before
BiFunction<Integer, Integer, Integer> calculateDiff = isAscending
? (currentLevel, nextLevel) -> nextLevel - currentLevel
: (currentLevel, nextLevel) -> currentLevel - nextLevel;
for (int levelIdx = 0; levelIdx < levels.length - 1; levelIdx++) {
int diff = calculateDiff.apply(levels[levelIdx], levels[levelIdx + 1]);
if (!isSafeStep(diff)) {
return false;
}
}
return true;
}
private static boolean isSafeStep(int diff) {
return 1 <= diff && diff <= 3;
}
}