Compare commits

...

3 Commits

Author SHA1 Message Date
e6867b9cfb feat: include 2020D7 2025-11-28 11:32:01 +01:00
d783d14ecc test: add PartOne unit test 2025-11-28 11:31:55 +01:00
1fe2e30ef8 feat: use a BFS approach to solve part one 2025-11-28 11:31:43 +01:00
3 changed files with 94 additions and 0 deletions

View File

@@ -10,6 +10,7 @@ import (
_ "advent-of-code/internal/2020/DayFour"
_ "advent-of-code/internal/2020/DayOne"
_ "advent-of-code/internal/2020/DaySeven"
_ "advent-of-code/internal/2020/DaySix"
_ "advent-of-code/internal/2020/DayThree"
_ "advent-of-code/internal/2020/DayTwo"

View File

@@ -0,0 +1,70 @@
package dayseven
import (
"advent-of-code/internal/registry"
"os"
"regexp"
"strings"
)
func init() {
registry.Register("2020D7", ParseInput, PartOne, PartTwo)
}
func ParseInput(filepath string) []string {
content, _ := os.ReadFile(filepath)
return strings.Split(string(content), "\n")
}
func PartOne(data []string) int {
reverseGraph := make(map[string][]string)
rulePattern := regexp.MustCompile(`^(\w+ \w+) bags contain (.+)\.$`)
containedPattern := regexp.MustCompile(`(\d+) (\w+ \w+) bags?`)
for _, line := range data {
matches := rulePattern.FindStringSubmatch(line)
if len(matches) != 3 {
continue
}
containerBag := matches[1]
containedString := matches[2]
if containedString == "no other bags" {
continue
}
containedMatches := containedPattern.FindAllStringSubmatch(containedString, -1)
for _, match := range containedMatches {
if len(match) >= 3 {
containedBag := match[2]
reverseGraph[containedBag] = append(reverseGraph[containedBag], containerBag)
}
}
}
visited := make(map[string]bool)
queue := reverseGraph["shiny gold"]
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
if visited[current] {
continue
}
visited[current] = true
for _, parent := range reverseGraph[current] {
if !visited[parent] {
queue = append(queue, parent)
}
}
}
return len(visited)
}
func PartTwo(data []string) int {
return 0
}

View File

@@ -0,0 +1,23 @@
package dayseven
import "testing"
var testInput = []string{
"light red bags contain 1 bright white bag, 2 muted yellow bags.",
"dark orange bags contain 3 bright white bags, 4 muted yellow bags.",
"bright white bags contain 1 shiny gold bag.",
"muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.",
"shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.",
"dark olive bags contain 3 faded blue bags, 4 dotted black bags.",
"vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.",
"faded blue bags contain no other bags.",
"dotted black bags contain no other bags.",
}
func TestPartOne(t *testing.T) {
expected := 4
got := PartOne(testInput)
if got != expected {
t.Errorf("PartOne() = %d, want %d", got, expected)
}
}