-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay04.java
More file actions
98 lines (82 loc) · 2.15 KB
/
Day04.java
File metadata and controls
98 lines (82 loc) · 2.15 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.List;
import java.util.ArrayList;
class Day04{
public static void Run(List<String> input){
ArrayList<ElfPair> elfPairs=new ArrayList<ElfPair>(input.size());
for(String line: input){
String[] pairs = line.split(",");
elfPairs.add(new ElfPair(
new SectionRange(pairs[0]),
new SectionRange(pairs[1])
));
}
System.out.println("04.1: "+P1(elfPairs));
System.out.println("04.2: "+P2(elfPairs));
} // Run
private static int P1(List<ElfPair> elfPairs){
int count=0;
for(ElfPair pair: elfPairs)
{
if (pair.getRange1().CompletelyContains(pair.getRange2())
|| pair.getRange2().CompletelyContains(pair.getRange1()))
{
count++;
}
}
return count;
}
private static int P2(List<ElfPair> elfPairs){
int count=0;
for(ElfPair pair: elfPairs)
{
if (pair.getRange1().Overlaps(pair.getRange2()))
{
count++;
}
}
return count;
}
}
class SectionRange{
private int _start;
private int _end;
public SectionRange(String rangeDescription)
{
// input string is in the form {start}-{end}
String[] startEnd=rangeDescription.split("-");
_start=Integer.parseInt(startEnd[0]);
_end=Integer.parseInt(startEnd[1]);
}
public SectionRange(int start, int end)
{
_start=start;
_end=end;
}
public boolean Contains(int sectionNumber)
{
return ((sectionNumber>=_start) && (sectionNumber <= _end));
}
public boolean CompletelyContains(SectionRange other)
{
return Contains(other._start) && Contains(other._end);
}
public boolean Overlaps(SectionRange other)
{
// this probably has some redundancy that could be optimized out
return Contains(other._start)
|| Contains(other._end)
|| other.Contains(_start)
|| other.Contains(_end);
}
}
class ElfPair{
SectionRange _range1;
SectionRange _range2;
public ElfPair(SectionRange range1, SectionRange range2)
{
_range1=range1;
_range2=range2;
}
public SectionRange getRange1(){return _range1;}
public SectionRange getRange2(){return _range2;}
}