day 7 part 2 solution (yay recursion)

This commit is contained in:
Colin McMillen 2020-12-07 14:47:24 -05:00
parent 217a59affb
commit 314eaa841a

View File

@ -64,6 +64,16 @@ namespace AdventOfCode {
} }
} }
static int CountBags(List<Contains> rules, string target) {
int total = 1;
foreach (Contains rule in rules) {
if (rule.Outer == target) {
total += rule.Count * CountBags(rules, rule.Inner);
}
}
return total;
}
static int Part1() { static int Part1() {
List<Contains> contains = ParseRules(File.ReadAllLines(Util.RootDir + "day07.txt")); List<Contains> contains = ParseRules(File.ReadAllLines(Util.RootDir + "day07.txt"));
return ComputePart1(contains); return ComputePart1(contains);
@ -71,7 +81,7 @@ namespace AdventOfCode {
static int Part2() { static int Part2() {
List<Contains> contains = ParseRules(File.ReadAllLines(Util.RootDir + "day07.txt")); List<Contains> contains = ParseRules(File.ReadAllLines(Util.RootDir + "day07.txt"));
return -1; return CountBags(contains, "shiny gold") - 1;
} }
[Fact] [Fact]
@ -88,9 +98,19 @@ faded blue bags contain no other bags.
dotted black bags contain no other bags.".Split('\n'); dotted black bags contain no other bags.".Split('\n');
Assert.Equal(4, ComputePart1(ParseRules(example))); Assert.Equal(4, ComputePart1(ParseRules(example)));
Assert.Equal(213, Part1()); Assert.Equal(213, Part1());
Assert.Equal(-1, Part2());
string[] example2 =
@"shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags.".Split('\n');
Assert.Equal(127, CountBags(ParseRules(example2), "shiny gold"));
Assert.Equal(38426, Part2());
} }
} }
} }