2016-day20: did an unnecessary merge ranges

This commit is contained in:
alexchao26
2020-12-24 18:41:02 -05:00
parent 5f678bc014
commit d1a81dcfcb
2 changed files with 94 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
package main
import (
"flag"
"fmt"
"math"
"sort"
"strings"
"github.com/alexchao26/advent-of-code-go/mathutil"
"github.com/alexchao26/advent-of-code-go/util"
)
func main() {
var part int
flag.IntVar(&part, "part", 1, "part 1 or 2")
flag.Parse()
fmt.Println("Running part", part)
ans := firewall(util.ReadFile("./input.txt"), part)
fmt.Println("Output:", ans)
}
func firewall(input string, part int) int {
var allBlockedRanges [][2]int
for _, line := range strings.Split(input, "\n") {
var r [2]int
fmt.Sscanf(line, "%d-%d", &r[0], &r[1])
allBlockedRanges = append(allBlockedRanges, r)
}
sort.Slice(allBlockedRanges, func(i, j int) bool {
if allBlockedRanges[i][0] != allBlockedRanges[j][0] {
return allBlockedRanges[i][0] < allBlockedRanges[j][0]
}
return allBlockedRanges[i][1] < allBlockedRanges[j][1]
})
// merge allBlockedRanges
merged := [][2]int{[2]int{}}
for _, r := range allBlockedRanges {
endOfLastRange := merged[len(merged)-1][1]
if endOfLastRange >= r[0]-1 {
merged[len(merged)-1][1] = mathutil.MaxInt(endOfLastRange, r[1])
} else {
merged = append(merged, r)
}
}
if part == 1 {
return merged[0][1] + 1
}
if merged[len(merged)-1][1] != math.MaxUint32 {
merged = append(merged, [2]int{math.MaxUint32, 0})
}
var totalAllowed int
for i := 1; i < len(merged); i++ {
totalAllowed += merged[i][0] - merged[i-1][1] - 1
}
return totalAllowed
}
+31
View File
@@ -0,0 +1,31 @@
package main
import (
"testing"
"github.com/alexchao26/advent-of-code-go/util"
)
var example = `5-8
0-2
4-7`
func Test_firewall(t *testing.T) {
tests := []struct {
name string
input string
part int
want int
}{
{"example part1", example, 1, 3},
{"actual part1", util.ReadFile("input.txt"), 1, 23923783},
{"actual part2", util.ReadFile("input.txt"), 2, 125},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := firewall(tt.input, tt.part); got != tt.want {
t.Errorf("firewall() = %v, want %v", got, tt.want)
}
})
}
}