package aoc2022

import println
import readInput

/*
--- Day 6: Tuning Trouble ---
https://adventofcode.com/2022/day/6
*/
fun main() {
    val inlineTestInput = """
mjqjpqmgbljsphdztnvjfqwrcgsmlb
"""

    fun detect(input: String, distinct: Int): Int {
        val countTab = HashMap<Char, Int>()
        val rempos = distinct - 1
        for (i in 0..input.lastIndex) {
            countTab.merge(input[i], 1) { v1, v2 -> v1 + v2 }
            if (countTab.size == distinct) return i + 1
            if (i >= rempos) {
                if (countTab[input[i - rempos]] == 1) {
                    countTab.remove(input[i - rempos])
                } else {
                    countTab.merge(input[i - rempos], -1) { v1, v2 -> v1 + v2 }
                }
            }
        }
        return -1
    }

    fun part1(input: List<String>): Int {
        return detect(input.first(), 4)
    }

    fun part2(input: List<String>): Int {
        return detect(input.first(), 14)
    }

    // test if implementation meets criteria from the description, like:
    val testInput = inlineTestInput.trim().reader().readLines()
    //val testInput = readInput("aoc2022/Day06_test")
    println("Part 1 Test: " + part1(testInput))
    println("Part 2 Test: " + part2(testInput))
    check(part1(testInput) == 7)
    check(part2(testInput) == 19)

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