From ceb3502c969f3032620a7e66b89aec4b3f007499 Mon Sep 17 00:00:00 2001 From: Kharec Date: Fri, 28 Nov 2025 12:02:14 +0100 Subject: [PATCH] refactor: prepare part two, which will use the same parsing logic + new structure --- internal/2020/DaySeven/code.go | 44 ++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/internal/2020/DaySeven/code.go b/internal/2020/DaySeven/code.go index 974d8cc..dbe562b 100644 --- a/internal/2020/DaySeven/code.go +++ b/internal/2020/DaySeven/code.go @@ -4,22 +4,26 @@ import ( "advent-of-code/internal/registry" "os" "regexp" + "strconv" "strings" ) +var ( + rulePattern = regexp.MustCompile(`^(\w+ \w+) bags contain (.+)\.$`) + containedPattern = regexp.MustCompile(`(\d+) (\w+ \w+) bags?`) +) + +type bagCount struct { + count int + bag string +} + 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?`) +func buildForwardGraph(data []string) map[string][]bagCount { + forwardGraph := make(map[string][]bagCount) for _, line := range data { matches := rulePattern.FindStringSubmatch(line) @@ -31,18 +35,38 @@ func PartOne(data []string) int { containedString := matches[2] if containedString == "no other bags" { + forwardGraph[containerBag] = []bagCount{} continue } containedMatches := containedPattern.FindAllStringSubmatch(containedString, -1) for _, match := range containedMatches { if len(match) >= 3 { + count, _ := strconv.Atoi(match[1]) containedBag := match[2] - reverseGraph[containedBag] = append(reverseGraph[containedBag], containerBag) + forwardGraph[containerBag] = append(forwardGraph[containerBag], bagCount{count: count, bag: containedBag}) } } } + return forwardGraph +} + +func ParseInput(filepath string) []string { + content, _ := os.ReadFile(filepath) + return strings.Split(string(content), "\n") +} + +func PartOne(data []string) int { + forwardGraph := buildForwardGraph(data) + reverseGraph := make(map[string][]string) + + for container, contained := range forwardGraph { + for _, child := range contained { + reverseGraph[child.bag] = append(reverseGraph[child.bag], container) + } + } + visited := make(map[string]bool) queue := reverseGraph["shiny gold"]