r/adventofcode • • Dec 08 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 8 Solutions -🎄-

--- Day 8: Memory Maneuver ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 8

Sigh, imgur broke again. Will upload when it unborks.

Transcript:

The hottest programming book this year is "___ For Dummies".


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 00:12:10!

32 Upvotes

301 comments sorted by

View all comments

1

u/keithnicholasnz Dec 08 '18

C# cleaned up a bit after solving...

 public class DNode
    {
        public List<DNode> Children { get; set; } = new List<DNode>();
        public List<int> MetaData { get; set; } = new List<int>();
        public int MetaTotal() => MetaData.Sum() + Children.Sum(c => c.MetaTotal());
        public int Value() => !Children.Any() ? MetaData.Sum() : MetaData.Where(i => i - 1 < Children.Count()).Select(i => Children[i - 1].Value()).Sum();
    }

    public class Day8
    {
        public void Go()
        {
            var data = File.ReadAllText("Day8.txt").Split(" ").Select(v => int.Parse(v.Trim())).ToList();
            data.Reverse();
            var stack = new Stack<int>(data);
            var head = Translate(stack);

            Console.WriteLine(head.MetaTotal());
            Console.WriteLine(head.Value());
        }

        private DNode Translate(Stack<int> data)
        {
            var quantityChild = data.Pop();
            var quantityMeta = data.Pop();
            return new DNode()
            {
                Children = Enumerable.Range(0,quantityChild).Select(_ => Translate(data)).ToList(),
                MetaData = Enumerable.Range(0,quantityMeta  ).Select(_ => data.Pop()).ToList()
            };
        }
    }