package aoc2022

import println
import readInput

/*
--- Day 3: Rucksack Reorganization ---
https://adventofcode.com/2022/day/3
*/
fun main() {

    val inlineTestInput = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
"""

    fun toPrio(input: Char) = if (input in 'A'..'Z') input - 'A' + 27 else input - 'a' + 1

    fun part1(input: List<String>): Int =
        input.sumOf {
            val seen = IntArray(2 * 26 + 1)
            it.subSequence(0, it.length / 2).forEach { seen[toPrio(it)] = 1 }
            it.subSequence(it.length / 2, it.length).forEach { seen[toPrio(it)] = seen[toPrio(it)] or 2 }
            seen.withIndex().find { it.value == 3 }!!.index
        }

    fun part2(input: List<String>): Int =
        input.chunked(3)
            .sumOf {
                val seen = IntArray(2 * 26 + 1)
                it[0].forEach { seen[toPrio(it)] = 1 }
                it[1].forEach { seen[toPrio(it)] = seen[toPrio(it)] or 2 }
                it[2].forEach { seen[toPrio(it)] = seen[toPrio(it)] or 4 }
                seen.withIndex().find { it.value == 7 }!!.index
            }

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

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