From 265072a72f6dc22dae4b4b18506f9827dea17440 Mon Sep 17 00:00:00 2001 From: Araozu Date: Mon, 11 Mar 2024 18:20:15 -0500 Subject: [PATCH] day 7 part 2 --- main.go | 2 +- solutions/day07.go | 40 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 418ebe6..6b8ad5d 100644 --- a/main.go +++ b/main.go @@ -26,7 +26,7 @@ func main() { runAndBenchmark("06", "2", false, solutions.Day06Part02) runAndBenchmark("07", "1", false, solutions.Day07Part01) - runAndBenchmark("07", "2", true, solutions.Day07Part02) + runAndBenchmark("07", "2", false, solutions.Day07Part02) } type execute func(bool) int diff --git a/solutions/day07.go b/solutions/day07.go index c1a0045..ea7fa57 100644 --- a/solutions/day07.go +++ b/solutions/day07.go @@ -9,6 +9,7 @@ type Bag struct { color string contents []BagContent containsShinyGold bool + contentsCount int } type BagContent struct { @@ -24,7 +25,7 @@ func parseBagStatement(bagStatement string) Bag { // if no aditional bags if bagContentsStr[:2] == "no" { - return Bag{color: bagColor, contents: make([]BagContent, 0)} + return Bag{color: bagColor, contents: make([]BagContent, 0), contentsCount: -1} } // parse remainder bags @@ -53,7 +54,7 @@ func parseBagStatement(bagStatement string) Bag { bag color = word, word */ - return Bag{color: bagColor, contents: bagContents} + return Bag{color: bagColor, contents: bagContents, contentsCount: -1} } func bagContainsShinyGold(bag *Bag, bagMap map[string]Bag) bool { @@ -103,6 +104,37 @@ func Day07Part01(isTest bool) int { return shinyGoldContainers } -func Day07Part02(isTest bool) int { - return -1 +func countInnerBags(bag *Bag, bagMap map[string]Bag) int { + if bag.contentsCount != -1 { + return bag.contentsCount + } + + innerBagsCount := 0 + + // recursively count bags + for _, nextBagStruct := range bag.contents { + nextBagCount := nextBagStruct.count + nextBag := bagMap[nextBagStruct.color] + + innerBagsCount += nextBagCount + nextBagCount*countInnerBags(&nextBag, bagMap) + } + + return innerBagsCount +} + +func Day07Part02(isTest bool) int { + input := ReadInput("07", isTest) + groups := strings.Split(input, "\n") + + bags := make(map[string]Bag) + + // parse and collect the bags + for _, statement := range groups { + parsedBag := parseBagStatement(statement) + bags[parsedBag.color] = parsedBag + } + + shinyGoldBag := bags["shiny gold"] + + return countInnerBags(&shinyGoldBag, bags) }