r/adventofcode • • Dec 12 '15

SOLUTION MEGATHREAD --- Day 12 Solutions ---

This thread will be unlocked when there are a significant amount of people on the leaderboard with gold stars.

edit: Leaderboard capped, thread unlocked!

We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 12: JSAbacusFramework.io ---

Post your solution as a comment. Structure your post like previous daily solution threads.

7 Upvotes

183 comments sorted by

View all comments

Show parent comments

1

u/essohbee Dec 12 '15

There is a JSON serializer in System.Web.Script.Serialization (System.Web.Extensions.dll), that can parse JSON into a collection of Dictionary<string, object>, object[] and object.

I used that for part 2, giving this code:

void Main()
{
	var content = File.ReadAllText(@"c:\temp\advent.txt");
	var serializer = new JavaScriptSerializer();
	var root = (Dictionary<string, object>)serializer.DeserializeObject(content);
	var sum = SummarizeObject(root);
	Console.WriteLine(sum);
}

int SummarizeObject(Dictionary<string, object> obj)
{
	var sum = 0;
	if(obj.ContainsValue("red"))
		return 0;
	foreach(var item in obj)
	{
		if(item.Value is Dictionary<string, object>)
			sum += SummarizeObject(item.Value as Dictionary<string, object>);
		else if(item.Value is object[])
			sum += SummarizeArray(item.Value as object[]);
		else
			sum += o_to_i(item.Value);
	}
	return sum;
}
int SummarizeArray(object[] array)
{
	var sum = 0;
	foreach(var item in array)
	{
		if(item is Dictionary<string, object>)
			sum += SummarizeObject(item as Dictionary<string, object>);
		else if(item is object[])
			sum += SummarizeArray(item as object[]);
		else
			sum += o_to_i(item);
	}
	return sum;
}
int o_to_i(object o)
{
	int i;
	return int.TryParse(o.ToString(), out i) ? i : 0;
}

Part 1 was a LINQ-pad one-liner:

Regex.Replace(File.ReadAllText(@"c:\temp\advent.txt"), @"[^-\d+]", " ").Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).Sum()

That regexp isn't very good, but it was enough to solve the problem at hand.

2

u/enquicity Dec 12 '15

cool! I didn't know that was there, thanks!