Created
December 7, 2020 20:20
-
-
Save felix-larsen/52695bb1f8fcf37a364b10c602b3f192 to your computer and use it in GitHub Desktop.
7th December solution - Advent of Code - swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var list = listBagsContaining(with: bagMap, withBagName: "shinygold", allBagNames: [String]()) | |
func listBagsContaining(with bags: [String : [Bag]], withBagName bagName: String, allBagNames: [String]) -> [String] { | |
let containingBagNames = bags.filter { | |
key, value in | |
value.map({ $0.name}).contains(bagName) | |
} | |
.compactMap { $0.key } | |
if containingBagNames.count == 0 { | |
return allBagNames + [bagName] | |
} else { | |
return allBagNames + containingBagNames.flatMap({ bag in | |
return listBagsContaining(with: bags, withBagName: bag, allBagNames: allBagNames + [bagName]) | |
}) | |
} | |
} | |
// subtract one as shiny gold bag is not counted | |
print(Set(list).count - 1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var shinyGoldCount = countBagsContained(with: bagMap, in: Bag(name: "shinygold", count: 1), startCount: 0) | |
func countBagsContained(with bags : [String : [Bag]], in bag: Bag, startCount: Int) -> Int { | |
let containingBagNames = bags[bag.name] | |
if containingBagNames?.count == 0 || containingBagNames == nil { | |
return startCount | |
} else { | |
return startCount + bag.count * containingBagNames!.reduce(0,{ start, aBag in | |
return start + countBagsContained(with: bags, in: aBag, startCount: aBag.count) | |
}) | |
} | |
} | |
print(shinyGoldCount) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment