day 7 part 2

master
Araozu 2024-03-11 18:20:15 -05:00
parent a44fa890c7
commit 265072a72f
2 changed files with 37 additions and 5 deletions

View File

@ -26,7 +26,7 @@ func main() {
runAndBenchmark("06", "2", false, solutions.Day06Part02) runAndBenchmark("06", "2", false, solutions.Day06Part02)
runAndBenchmark("07", "1", false, solutions.Day07Part01) runAndBenchmark("07", "1", false, solutions.Day07Part01)
runAndBenchmark("07", "2", true, solutions.Day07Part02) runAndBenchmark("07", "2", false, solutions.Day07Part02)
} }
type execute func(bool) int type execute func(bool) int

View File

@ -9,6 +9,7 @@ type Bag struct {
color string color string
contents []BagContent contents []BagContent
containsShinyGold bool containsShinyGold bool
contentsCount int
} }
type BagContent struct { type BagContent struct {
@ -24,7 +25,7 @@ func parseBagStatement(bagStatement string) Bag {
// if no aditional bags // if no aditional bags
if bagContentsStr[:2] == "no" { 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 // parse remainder bags
@ -53,7 +54,7 @@ func parseBagStatement(bagStatement string) Bag {
bag color = word, word 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 { func bagContainsShinyGold(bag *Bag, bagMap map[string]Bag) bool {
@ -103,6 +104,37 @@ func Day07Part01(isTest bool) int {
return shinyGoldContainers return shinyGoldContainers
} }
func Day07Part02(isTest bool) int { func countInnerBags(bag *Bag, bagMap map[string]Bag) int {
return -1 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)
} }