package aoc2015

import CharGrid
import println
import readInput

/*
--- Day 6: Probably a Fire Hazard ---
https://adventofcode.com/2015/day/6
*/
fun main() {

    fun part1(input: List<String>): Int {
        val grid = CharGrid(1000, 1000)
        input.forEach {
            val (op, x1, y1, x2, y2) = "(toggle|turn off|turn on) (\\d+),(\\d+) through (\\d+),(\\d+)".toRegex().matchEntire(it)!!.destructured
            for (y in y1.toInt()..y2.toInt()) {
                for (x in x1.toInt()..x2.toInt()) {
                    grid[x, y] = when (op) {
                        "turn on" -> '*'
                        "turn off" -> ' '
                        "toggle" -> if (grid[x, y] == '*') ' ' else '*'
                        else -> throw IllegalStateException()
                    }
                }
            }
        }
        return grid.generateGridPos().count { grid[it] == '*' }
    }

    fun part2(input: List<String>): Int {
        val grid = IntArray(1000 * 1000)
        input.forEach {
            val (op, x1, y1, x2, y2) = "(toggle|turn off|turn on) (\\d+),(\\d+) through (\\d+),(\\d+)".toRegex().matchEntire(it)!!.destructured
            for (y in y1.toInt()..y2.toInt()) {
                for (x in x1.toInt()..x2.toInt()) {
                    grid[x + y * 1000] = (grid[x + y * 1000] + when (op) {
                        "turn on" -> 1
                        "turn off" -> -1
                        "toggle" -> 2
                        else -> throw IllegalStateException()
                    }).coerceAtLeast(0)
                }
            }
        }
        return grid.sum()
    }

    val input = readInput("aoc2015/Day06")
    part1(input).println()
    part2(input).println()
}
