-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAoC2022_04.java
More file actions
76 lines (62 loc) · 2.33 KB
/
AoC2022_04.java
File metadata and controls
76 lines (62 loc) · 2.33 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
72
73
74
75
76
import java.util.List;
import java.util.function.BiPredicate;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import com.github.pareronia.aoc.RangeInclusive;
import com.github.pareronia.aocd.Aocd;
import com.github.pareronia.aocd.Puzzle;
public class AoC2022_04 extends AoCBase {
private static final Pattern REGEX = Pattern.compile("[0-9]+");
private final List<String> input;
private AoC2022_04(final List<String> input, final boolean debug) {
super(debug);
this.input = input;
}
public static final AoC2022_04 create(final List<String> input) {
return new AoC2022_04(input, false);
}
public static final AoC2022_04 createDebug(final List<String> input) {
return new AoC2022_04(input, true);
}
private final int[] numbers(final String string) {
return REGEX.matcher(string).results()
.map(MatchResult::group)
.mapToInt(Integer::parseInt)
.toArray();
}
private int solve(final BiPredicate<RangeInclusive<Integer>, RangeInclusive<Integer>> predicate) {
return (int) this.input.stream()
.map(this::numbers)
.filter(nums -> predicate.test(
RangeInclusive.between(nums[0], nums[1]),
RangeInclusive.between(nums[2], nums[3])))
.count();
}
@Override
public Integer solvePart1() {
return solve((range1, range2) ->
range1.containsRange(range2) || range2.containsRange(range1));
}
@Override
public Integer solvePart2() {
return solve((range1, range2) -> range1.isOverlappedBy(range2));
}
public static void main(final String[] args) throws Exception {
assert AoC2022_04.createDebug(TEST).solvePart1() == 2;
assert AoC2022_04.createDebug(TEST).solvePart2() == 4;
final Puzzle puzzle = Aocd.puzzle(2022, 4);
final List<String> inputData = puzzle.getInputData();
puzzle.check(
() -> lap("Part 1", AoC2022_04.create(inputData)::solvePart1),
() -> lap("Part 2", AoC2022_04.create(inputData)::solvePart2)
);
}
private static final List<String> TEST = splitLines("""
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
""");
}