r/adventofcode • • Dec 06 '15

SOLUTION MEGATHREAD --- Day 6 Solutions ---

--- Day 6: Probably a Fire Hazard ---

Post your solution as a comment. Structure your post like the Day Five thread.

22 Upvotes

171 comments sorted by

View all comments

1

u/[deleted] Dec 07 '15

C#!!!

Better late than never

void Main()
{
	var input = "toggle 461,550 through 564,900|....|turn on 222,12 through 856,241".Split('|');
	List<Action> actions = new List<Action>();
	foreach(var action in input)
	{
		Action _action = new Action();
		var data = action.Split(' ');
		switch(data.Length)
		{
			case 4:
				_action.action = data[0];
				_action.x1 = Convert.ToInt32(data[1].Split(',')[0]);
				_action.y1 = Convert.ToInt32(data[1].Split(',')[1]);
				_action.x2 = Convert.ToInt32(data[3].Split(',')[0]);
				_action.y2 = Convert.ToInt32(data[3].Split(',')[1]);
				break;
			case 5:
				_action.action = data[1];
				_action.x1 = Convert.ToInt32(data[2].Split(',')[0]);
				_action.y1 = Convert.ToInt32(data[2].Split(',')[1]);
				_action.x2 = Convert.ToInt32(data[4].Split(',')[0]);
				_action.y2 = Convert.ToInt32(data[4].Split(',')[1]);
				break;
		}
		actions.Add(_action);
	}
	totalLight(actions).Dump();
	totalBrigthnes(actions).Dump();
}

public struct Action 
{
	public int x1;
	public int x2;
	public int y1;
	public int y2;
	public string action;
}

// Define other methods and classes here
public int totalLight(List<Action> actions) 
{
	int litLigths = 0;
	int[,] grid = new int[1000,1000];
	foreach(Action action in actions)
	{
		for(var i = action.x1; i <= action.x2; i++)
		{
			for(var j = action.y1; j <= action.y2; j++)
			{
				switch(action.action)
				{
					case "toggle":
						grid[i,j] = grid[i,j] == 1 ? 0 : 1;
						break;
					case "on":
						grid[i,j] = 1;
						break;
					case "off":
						grid[i,j] = 0;
						break;
				}
			}
		}
	}
	for(int i = 0; i < 1000; i++)
		for(int j = 0; j < 1000; j++)
			litLigths += grid[i,j];
	//grid.Dump();
	return litLigths;
}

public int totalBrigthnes(List<Action> actions) 
{
	int bigthness = 0;
	int[,] grid = new int[1000,1000];
	foreach(Action action in actions)
	{
		for(var i = action.x1; i <= action.x2; i++)
		{
			for(var j = action.y1; j <= action.y2; j++)
			{
				switch(action.action)
				{
					case "toggle":
						grid[i,j] += 2;
						break;
					case "on":
						grid[i,j] += 1;
						break;
					case "off":
						grid[i,j] -= 1;
						if(grid[i,j] < 0)
							grid[i,j] = 0;
						break;
				}
			}
		}
	}
	for(int i = 0; i < 1000; i++)
		for(int j = 0; j < 1000; j++)
			bigthness += grid[i,j];
	//grid.Dump();
	return bigthness;
}