Skip to content

Commit 5e2806b

Browse files
committed
2022/04 comment
1 parent de703ec commit 5e2806b

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

2022/Day04/Solution.cs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,37 @@ namespace AdventOfCode.Y2022.Day04;
55

66
[ProblemName("Camp Cleanup")]
77
class Solution : Solver {
8-
public object PartOne(string input) => DuplicateWorkCount(input, Contains);
9-
public object PartTwo(string input) => DuplicateWorkCount(input, Overlaps);
8+
public object PartOne(string input) => DuplicatedWorkCount(input, Contains);
9+
public object PartTwo(string input) => DuplicatedWorkCount(input, Overlaps);
1010

1111
record struct Range(int from, int to);
12+
13+
// True if r1 contains r2 [ { } ]
1214
bool Contains(Range r1, Range r2) => r1.from <= r2.from && r2.to <= r1.to;
15+
16+
// True if r1 overlaps r2 { [ } ], the other direction is not checked.
1317
bool Overlaps(Range r1, Range r2) => r1.to >= r2.from && r1.from <= r2.to;
1418

15-
private int DuplicateWorkCount(string input, Func<Range, Range, bool> rangeCheck) {
19+
// DuplicatedWorkCount goes over the lines in the input, converts them to
20+
// ranges A and B, and counts how many times rangeCheck(A,B) or
21+
// rangeCheck(B, A) is true. The check is applied in both ways so that the
22+
// Contains and Overlaps functions don't have to check each directions.
23+
private int DuplicatedWorkCount(
24+
string input,
25+
Func<Range, Range, bool> rangeCheck
26+
) {
27+
// '36-41,35-40' becomes [Range(36, 41), Range(35, 40)]
1628
var parseRanges = (string line) =>
1729
from range in line.Split(',')
1830
let fromTo = range.Split('-').Select(int.Parse)
1931
select new Range(fromTo.First(), fromTo.Last());
2032

21-
return input.Split("\n").Select(parseRanges).Count(ranges =>
22-
rangeCheck(ranges.First(), ranges.Last()) ||
23-
rangeCheck(ranges.Last(), ranges.First())
24-
);
33+
return input
34+
.Split("\n")
35+
.Select(parseRanges)
36+
.Count(ranges =>
37+
rangeCheck(ranges.First(), ranges.Last()) ||
38+
rangeCheck(ranges.Last(), ranges.First())
39+
);
2540
}
2641
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy