1
+ package com .macasaet ;
2
+
3
+ import org .junit .jupiter .api .Test ;
4
+
5
+ import java .util .stream .Stream ;
6
+ import java .util .stream .StreamSupport ;
7
+
8
+ /**
9
+ * --- Day 4: Camp Cleanup ---
10
+ * <a href="https://adventofcode.com/2022/day/4">https://adventofcode.com/2022/day/4</a>
11
+ */
12
+ public class Day04 {
13
+
14
+ /**
15
+ * One crew member responsible for cleaning up the camp. They are responsible for a contiguous range of sections.
16
+ *
17
+ * @param sectionMin the lowest section ID for which this Elf is responsible (inclusive)
18
+ * @param sectionMax the highest section ID for which this Elf is responsible (inclusive).
19
+ */
20
+ public record Elf (int sectionMin , int sectionMax ) {
21
+
22
+ public boolean fullyContains (final Elf other ) {
23
+ return sectionMin () <= other .sectionMin () && sectionMax () >= other .sectionMax ();
24
+ }
25
+
26
+ public static Elf parse (final String string ) {
27
+ final var components = string .split ("-" );
28
+ return new Elf (Integer .parseInt (components [0 ]), Integer .parseInt (components [1 ]));
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Two elves (of a larger crew) assigned to clean up the camp.
34
+ */
35
+ public record Pair (Elf left , Elf right ) {
36
+ public boolean oneFullyContainsTheOther () {
37
+ return left .fullyContains (right ) || right .fullyContains (left );
38
+ }
39
+ public boolean hasOverlap () {
40
+ return (left .sectionMin () <= right .sectionMin () && left .sectionMax () >= right .sectionMin ())
41
+ || (right .sectionMin () <= left .sectionMin () && right .sectionMax () >= left .sectionMin ());
42
+ }
43
+ public static Pair parse (final String line ) {
44
+ final var components = line .split ("," );
45
+ return new Pair (Elf .parse (components [0 ]), Elf .parse (components [1 ]));
46
+ }
47
+ }
48
+ protected Stream <Pair > getInput () {
49
+ return StreamSupport
50
+ .stream (new LineSpliterator ("day-04.txt" ),
51
+ false )
52
+ .map (Pair ::parse );
53
+ }
54
+
55
+ @ Test
56
+ public final void part1 () {
57
+ final var result = getInput ().filter (Pair ::oneFullyContainsTheOther ).count ();
58
+
59
+ System .out .println ("Part 1: " + result );
60
+ }
61
+
62
+ @ Test
63
+ public final void part2 () {
64
+ final var result = getInput ().filter (Pair ::hasOverlap ).count ();
65
+
66
+ System .out .println ("Part 2: " + result );
67
+ }
68
+
69
+ }
0 commit comments