feat: solve day 5 part 2

This commit is contained in:
Stevan Freeborn
2025-12-10 04:56:55 -06:00
parent 36c3b8eaf3
commit b3b0b2cdba
2 changed files with 64 additions and 1 deletions
+44 -1
View File
@@ -74,13 +74,56 @@ func SolvePartOne(filePath string) int {
total := 0
for _, id := range ids {
for _, rnge := range ranges {
for _, rnge := range mergedRanges {
if id >= rnge.start && id <= rnge.end {
total++
break
}
}
}
return total
}
func SolvePartTwo(filePath string) int64 {
input := file.ReadAllLines(filePath)
ranges := []rnge{}
for _, line := range input {
if line == "" {
break
}
rnge := NewRange(line)
ranges = append(ranges, rnge)
}
slices.SortFunc(ranges, func(a rnge, b rnge) int {
return cmp.Compare(a.start, b.start)
})
mergedRanges := []rnge{
ranges[0],
}
for _, currentRange := range ranges {
lastMergedRange := mergedRanges[len(mergedRanges)-1]
if currentRange.start > lastMergedRange.end {
mergedRanges = append(mergedRanges, currentRange)
continue
}
lastMergedRange.end = int64(math.Max(float64(lastMergedRange.end), float64(currentRange.end)))
mergedRanges[len(mergedRanges)-1] = lastMergedRange
}
total := int64(0)
for _, rnge := range mergedRanges {
diff := (rnge.end - rnge.start) + 1
total += diff
}
return total
+20
View File
@@ -25,3 +25,23 @@ func TestSolvePartOneWithInput(t *testing.T) {
t.Errorf("SolvePartOne with input: expected %d, got %d", expected, result)
}
}
func TestSolvePartTwoWithExampleInput(t *testing.T) {
expected := int64(14)
result := solution.SolvePartTwo("EXAMPLE.txt")
if result != expected {
t.Errorf("SolvePartTwo with example input: expected %d, got %d", expected, result)
}
}
func TestSolvePartTwoWithInput(t *testing.T) {
expected := int64(342_018_167_474_526)
result := solution.SolvePartTwo("INPUT.txt")
if result != expected {
t.Errorf("SolvePartTwo with input: expected %d, got %d", expected, result)
}
}