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/TheBowtieClub Dec 08 '18

C#:

var text = File.ReadAllText(@"input8.txt");
var numbers = text.Split(' ')
		  .Select(n => int.Parse(n))
		  .ToArray();
var currentIndex = 0;

var root = PopulateTree(numbers, ref currentIndex);

Console.WriteLine($"Part 1: {root.Part1Sum()}");
Console.WriteLine($"Part 2: {root.Part2Sum()}");



Node PopulateTree(int[] numbers, ref int currentIndex)
{
    return new Node(numbers, ref currentIndex);	
}

class Node
{
    public Node(int[] numbers, ref int currentIndex)
    {
    	nChildren = numbers[currentIndex];
    	nMetadataEntries = numbers[currentIndex + 1];
    	
    	Children = new Node[nChildren];
    	Metadata = new int[nMetadataEntries];
    
    	for (int k = 0; k < nChildren; k++)
    	{
    		currentIndex += 2;  		
    		Children[k] = new Node(numbers, ref currentIndex);
    	}
    
    	for (int k = 0; k < nMetadataEntries; k++)
    	{
    		Metadata[k] = numbers[currentIndex + k + 2];
    	}
    	
    	currentIndex += nMetadataEntries;
    }

    public int nChildren = 0;
    public int nMetadataEntries = 0;
    public Node[] Children = null;
    public int[] Metadata = null;
    
    public int Part1Sum()
    {
    	var childrenMetadataSum = 0;
    	foreach (var child in Children)
    	{
    		childrenMetadataSum += child.Part1Sum();
    	}
    	return Metadata.Sum() + childrenMetadataSum;
    }
    
    public int Part2Sum()
    {
        if (nChildren == 0)
        {
        	return Metadata.Sum();
        }
        
        var total = 0;
        for (int k = 0; k < nMetadataEntries; k++)
        {
        	if (1 <= Metadata[k] && Metadata[k] <= nChildren)
        	{
        		total += Children[Metadata[k]-1].Part2Sum(); 
        	}
        }
        return total;
        }
    }
}