Skip to content

Commit 1038a9d

Browse files
committed
2025/05
1 parent a8cacf8 commit 1038a9d

1 file changed

Lines changed: 7 additions & 15 deletions

File tree

2025/Day05/Solution.cs

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,16 @@ public object PartOne(string input) {
1515
}
1616

1717
public object PartTwo(string input) {
18-
// Merge overlapping ranges into disjoint intervals. First sort ranges
19-
// by start so that any range that can extend the current one appears at
20-
// a higher index. Then we walk the list once extending ranges[i] with any
21-
// later range that overlaps with it.
18+
// Sort ranges by start so that potentionally overlapping ranges come after
19+
// each other. Then walk the list and make them disjoint:
2220
var ranges = Parse(input).ranges.OrderBy(x => x.start).ToList();
23-
24-
for (var i = 0; i < ranges.Count; i++) {
25-
int j = i + 1;
26-
while (j < ranges.Count) {
27-
if (ranges[j].start <= ranges[i].end) {
28-
ranges[i] = new Range(ranges[i].start, Math.Max(ranges[i].end, ranges[j].end));
29-
ranges.RemoveAt(j);
30-
} else {
31-
j++;
32-
}
21+
for (var i = 0; i < ranges.Count - 1; i++) {
22+
if (ranges[i+1].start <= ranges[i].end) {
23+
var end = Math.Max(ranges[i].end, ranges[i + 1].end);
24+
ranges[i] = new Range(ranges[i].start, ranges[i+1].start - 1);
25+
ranges[i+1] = new Range(ranges[i+1].start, end);
3326
}
3427
}
35-
3628
return ranges.Sum(range => range.end - range.start + 1);
3729
}
3830

0 commit comments

Comments
 (0)