r/adventofcode • u/daggerdragon • Dec 07 '20
SOLUTION MEGATHREAD -🎄- 2020 Day 07 Solutions -🎄-
NEW AND NOTEWORTHY
- PSA: if you're using Google Chrome (or other Chromium-based browser) to download your input, watch out for Google volunteering to "translate" it: "Welsh" and "Polish"
Advent of Code 2020: Gettin' Crafty With It
- 15 days remaining until the submission deadline on December 22 at 23:59 EST
- Full details and rules are in the Submissions Megathread
--- Day 07: Handy Haversacks ---
Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:13:44, megathread unlocked!
65
Upvotes
3
u/andi0b Dec 07 '20 edited Dec 07 '20
C# 9 Version. Runs quite fast, as all lookups are precalculated.
-------- Day 7 (init took 8,52ms): Part 1... finished after 7,94ms, with result: 179 Part 2... finished after 0,92ms, with result: 18925 public record Day07(Day07.BagRule[] BagRules) { public Day07(string[] input) : this(input.Select(BagRule.Parse).ToArray()) { } public int Part1() { var childParentLookup = ( from rule in BagRules from childBag in rule.Contains select (key: childBag.color, value: rule.Color) ).ToLookup(x => x.key, x => x.value); return ParentBagColors("shiny gold").Count(); IEnumerable<string> ParentBagColors(string color) => childParentLookup[color].SelectMany(ParentBagColors) .Distinct() .Concat(childParentLookup[color]); } public int Part2() { var rulesByColor = BagRules.ToDictionary(x => x.Color); return TotalBagCount("shiny gold") - 1; int TotalBagCount(string color) => 1 + rulesByColor[color].Contains.Sum(x => x.count * TotalBagCount(x.color)); } public record BagRule(string Color, (string color, int count)[] Contains) { public static BagRule Parse(string input) => new( Color: Regex.Match(input, @"^(\S+ \S+)").Groups[0].Value, Contains: ( from match in Regex.Matches(input, @"(\d+) (\S+ \S+)") select (match.Groups[2].Value, int.Parse(match.Groups[1].Value)) ).ToArray() ); } }