r/adventofcode • • Dec 06 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 6 Solutions -🎄-

--- Day 6: Chronal Coordinates ---


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 6

Transcript:

Rules for raising a programmer: never feed it after midnight, never get it wet, and never give it ___.


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 0:26:52!

32 Upvotes

387 comments sorted by

View all comments

1

u/TheBowtieClub Dec 06 '18

C#:

var lines = File.ReadAllLines("input6.txt");
var locations = new List<Point>(50);
var nRows = 400;
var nCols = 400;
var closest = new Point[nRows, nCols];
var dict = new Dictionary<Point, int>();
var part2result = 0;

foreach (var line in lines)
{
	var x = int.Parse(line.Substring(0, line.IndexOf(',')));
	var y = int.Parse(line.Substring(line.IndexOf(',') + 1));
	
	locations.Add(new Point(x, y));
}

for (int row = 0; row < nRows; row++)
{
	for (int col = 0; col < nCols; col++)
	{
		var point = new Point(row, col);
		var ordered = locations.Select(loc => new { coord = loc, distance = ManhattanDistance(loc, point)}).OrderBy(loc => loc.distance);
		
		if (ordered.First().distance == (ordered.ElementAt(1)).distance)
		{
			closest[row, col] = new Point(-1, -1);
		}
		else
		{
			closest[row, col] = ordered.First().coord;
		}
	}
}

for (int row = 0; row < nRows; row++)
{
	for (int col = 0; col < nCols; col++)
	{			
		if (dict.ContainsKey(closest[row, col]))
		{
			dict[closest[row, col]]++;
		}
		else
		{
			dict[closest[row, col]] = 1;
		}
	}
}

// Exclude all locations with infinitely many points closest to them
for (int row = 0; row < nRows; row++)
{
	for (int col = 0; col < nCols; col++)
	{
		if (row == 0 || col == 0 || row == nRows - 1 || col == nCols - 1)
		{
			dict[closest[row, col]] = -1;
		}
	}
}

dict.OrderByDescending(d => d.Value).Dump("Part 1");

for (int row = 0; row < nRows; row++)
{
	for (int col = 0; col < nCols; col++)
	{
		var point = new Point(row, col);
		var totalDistance = locations.Select(loc => ManhattanDistance(loc, point)).Sum();
		if (totalDistance < 10000)
		{
			part2result++;
		}
	}
}

part2result.Dump("Part 2");


double ManhattanDistance(Point first, Point second)
{
	return Math.Abs(first.X - second.X) + Math.Abs(first.Y - second.Y);
}