improve performance of day 7 part 1
This commit is contained in:
parent
265072a72f
commit
a1018af799
@ -57,21 +57,20 @@ func parseBagStatement(bagStatement string) Bag {
|
|||||||
return Bag{color: bagColor, contents: bagContents, contentsCount: -1}
|
return Bag{color: bagColor, contents: bagContents, contentsCount: -1}
|
||||||
}
|
}
|
||||||
|
|
||||||
func bagContainsShinyGold(bag *Bag, bagMap map[string]Bag) bool {
|
func bagContainsShinyGold(bagColor string, bagMap map[string]Bag) bool {
|
||||||
|
bag := bagMap[bagColor]
|
||||||
if bag.containsShinyGold {
|
if bag.containsShinyGold {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// recursively search
|
// recursively search
|
||||||
for _, bagName := range bag.contents {
|
for _, nextBag := range bag.contents {
|
||||||
if bagName.color == "shiny gold" {
|
if nextBag.color == "shiny gold" {
|
||||||
bag.containsShinyGold = true
|
bag.containsShinyGold = true
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
nextBag := bagMap[bagName.color]
|
if bagContainsShinyGold(nextBag.color, bagMap) {
|
||||||
|
|
||||||
if bagContainsShinyGold(&nextBag, bagMap) {
|
|
||||||
bag.containsShinyGold = true
|
bag.containsShinyGold = true
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@ -85,18 +84,20 @@ func Day07Part01(isTest bool) int {
|
|||||||
groups := strings.Split(input, "\n")
|
groups := strings.Split(input, "\n")
|
||||||
|
|
||||||
bags := make(map[string]Bag)
|
bags := make(map[string]Bag)
|
||||||
|
bagColors := make([]string, len(groups))
|
||||||
|
|
||||||
// parse and collect the bags
|
// parse and collect the bags
|
||||||
for _, statement := range groups {
|
for i, statement := range groups {
|
||||||
parsedBag := parseBagStatement(statement)
|
parsedBag := parseBagStatement(statement)
|
||||||
bags[parsedBag.color] = parsedBag
|
bags[parsedBag.color] = parsedBag
|
||||||
|
bagColors[i] = parsedBag.color
|
||||||
}
|
}
|
||||||
|
|
||||||
shinyGoldContainers := 0
|
shinyGoldContainers := 0
|
||||||
|
|
||||||
// process the bags
|
// process the bags
|
||||||
for _, bag := range bags {
|
for _, bagColor := range bagColors {
|
||||||
if bagContainsShinyGold(&bag, bags) {
|
if bagContainsShinyGold(bagColor, bags) {
|
||||||
shinyGoldContainers += 1
|
shinyGoldContainers += 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user