package com.ukdave.adventofcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Advent of Code - Day 6 Part 2.
 * 
 * @author uk_dave
 */
public class Day6_Part2 {

	public static void main(final String[] args) throws IOException {
		int[][] lights = new int[1000][1000];
		
		try (BufferedReader br = new BufferedReader(new InputStreamReader(Day6_Part2.class.getResourceAsStream("/day6.txt")))) {
			Pattern p = Pattern.compile("(.*) ([0-9]+),([0-9]+) through ([0-9]+),([0-9]+)");
			for (String line = br.readLine(); line != null; line = br.readLine()) {
				Matcher m = p.matcher(line);
				if (!m.matches()) {
					continue;
				}
				
				String mode = m.group(1);
				int startX = Integer.parseInt(m.group(2));
				int startY = Integer.parseInt(m.group(3));
				int endX = Integer.parseInt(m.group(4));
				int endY = Integer.parseInt(m.group(5));
				
				for (int x = startX; x <= endX; x++) {
					for (int y = startY; y <= endY; y++) {
						if (mode.equals("turn on")) {
							lights[x][y]++;
						} else if (mode.equals("turn off")) {
							lights[x][y]--;
							if (lights[x][y] < 0) {
								lights[x][y] = 0;
							}
						} else if (mode.equals("toggle")) {
							lights[x][y] += 2;
						}
					}
				}
			}
		}
		
		int totalBrightness = 0;
		for (int x = 0; x < 1000; x++) {
			for (int y = 0; y < 1000; y++) {
				totalBrightness += lights[x][y];
			}
		}
		System.out.println(totalBrightness); // 14687245
	}
}

@@ -43,25 +43,83 @@
 ava.
-io.BufferedReader
+awt.image.BufferedImage;%0Aimport java.io.BufferedReader;%0Aimport java.io.File
 ;%0Aim
@@ -243,16 +243,47 @@
 ttern;%0A%0A
+import javax.imageio.ImageIO;%0A%0A
 /**%0A * A
@@ -1467,16 +1467,41 @@
 ss = 0;%0A
+%09%09int maxBrightness = 0;%0A
 %09%09for (i
@@ -1567,22 +1567,21 @@
 ) %7B%0A%09%09%09%09
-totalB
+int b
 rightnes
@@ -1582,17 +1582,16 @@
 ghtness 
-+
 = lights
@@ -1598,21 +1598,133 @@
 %5Bx%5D%5By%5D;%0A
+%09%09%09%09totalBrightness += brightness;%0A%09%09%09%09if (brightness %3E maxBrightness) %7B%0A%09%09%09%09%09maxBrightness = brightness;%0A%09
 %09%09%09%7D%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%09Sy
@@ -1770,13 +1770,432 @@
 4687245%0A
+%09%09%0A%09%09%0A%09%09%0A%09%09%0A%09%09BufferedImage image = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_RGB);%0A%09%09float scale = 255 / maxBrightness;%0A%09%09for (int x = 0; x %3C 1000; x++) %7B%0A%09%09%09for (int y = 0; y %3C 1000; y++) %7B%0A%09%09%09%09int grey = Math.round(lights%5Bx%5D%5By%5D * scale);%0A%09%09%09%09int rgb = ((grey & 0xff) %3C%3C 16) + ((grey & 0xff) %3C%3C 8) + (grey & 0xff);%0A%09%09%09%09image.setRGB(x, y, rgb);%0A%09%09%09%7D%0A%09%09%7D%0A%09%09ImageIO.write(image, %22png%22, new File(%22day6.png%22));%0A
 %09%7D%0A%7D%0A

Add heatmap to day 6 solution