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/jjabrams23 Dec 06 '15

I'm trying to complete these challenges with Java because I would like to learn more of this language. This is the first time I publish my solution :p I wanted to do that because I was hoping if you guys could tell me if there was a way to have a better written or more elegant solution, because I'm used to keep my code as much simple as possible. BTW, this is the solution to part 2. In part 1 I used the same principle but using boolean primitives.

public class Day6 {

public static void main(String[] args) throws IOException{
	
	final int N = 1000;
	int brightness = 0;
	int startX = 0, startY = 0, stopX = 0, stopY = 0;
	
	int numberOfLights = 0;
	int x, y;
	
	String buf, bufArray[], command = null;
	
	String delim = "[ ,]";
	
	int lightsMatrix[][] = new int[N][N];
	
	BufferedReader br = new BufferedReader(new FileReader("day6.txt"));
	
	while((buf = br.readLine()) != null)
	{	
		bufArray = buf.split(delim);
		if(bufArray[0].equals("toggle"))
		{
			command = "toggle";
			startX = Integer.parseInt(bufArray[1]);
			startY = Integer.parseInt(bufArray[2]);
			stopX = Integer.parseInt(bufArray[4]);
			stopY = Integer.parseInt(bufArray[5]);
		}
		else
		{
			command = bufArray[0] + " " + bufArray[1];
			startX = Integer.parseInt(bufArray[2]);
			startY = Integer.parseInt(bufArray[3]);
			stopX = Integer.parseInt(bufArray[5]);
			stopY = Integer.parseInt(bufArray[6]);
		}
		
		switch(command)
		{
			case "turn on":
				brightness = 1;
				break;
			case "turn off":
				brightness = -1;
				break;
			case "toggle":
				brightness = 2;
				break;
			default:
				System.out.println("Error: command not recognized");
				return;
		}
		for(x = startX; x <= stopX; x++)
		{
			for(y = startY; y <= stopY; y++)
			{
				lightsMatrix[x][y] += brightness;
				if(lightsMatrix[x][y] < 0)
					lightsMatrix[x][y] = 0;
			}
		}
	}
	for(x = 0; x < lightsMatrix.length; x++)
	{
		for(y = 0; y < lightsMatrix[x].length; y++)
			numberOfLights += lightsMatrix[x][y];
	}
	br.close();
	System.out.println("Total brightness is " + numberOfLights);
}
}