package aoc2025

import println
import readInput

/*
--- Day 3: Lobby ---
https://adventofcode.com/2025/day/3
*/
fun main() {

    val inlineTestInput = """
987654321111111
811111111111119
234234234234278
818181911112111
"""

    val powTenTable = generateSequence(1L) { it * 10L }.take(20).toList().toLongArray()

    fun rec(i: String, si: Int, left: Int): Long {
        for (dig in 9 downTo 1) {
            val dp = i.indexOf('0' + dig, si)
            if (dp >= 0) {
                if (left == 0) {
                    return dig.toLong()
                } else {
                    val lastDigits = rec(i, dp + 1, left - 1)
                    if (lastDigits >= 0) return lastDigits + dig * powTenTable[left]
                }
            }
        }
        return -1L
    }

    fun part1(input: List<String>): Long {
        return input.sumOf { rec(it, 0, 1) }
    }

    fun part2(input: List<String>): Long {
        return input.sumOf { rec(it, 0, 11) }
    }

    // test if implementation meets criteria from the description, like:
    val testInput = inlineTestInput.trim().reader().readLines()
    //val testInput = readInput("aoc2025/Day03_test")
    val testInputPart1Result = part1(testInput)
    println("Part 1 Test: $testInputPart1Result")
    val testInputPart2Result = part2(testInput)
    println("Part 2 Test: $testInputPart2Result")
    check(testInputPart1Result == 357L)
    check(testInputPart2Result == 3121910778619L)

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