package aoc2024

import println
import readInput
import splitInts

/*
--- Day 2: Red-Nosed Reports ---
https://adventofcode.com/2024/day/2
*/
fun main() {

    val inlineTestInput = """
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9
"""

    fun checkGood(i: List<Int>): Boolean {
        val dir = i[1] - i[0]
        return if (dir < 0) {
            !i.runningReduce { acc, elem -> if ((elem < acc) and (elem >= acc - 3)) elem else Int.MIN_VALUE }
                .contains(Int.MIN_VALUE)
        } else if (dir > 0) {
            !i.runningReduce { acc, elem -> if ((elem > acc) && (elem <= acc + 3)) elem else Int.MAX_VALUE }
                .contains(Int.MAX_VALUE)
        } else {
            false
        }
    }

    fun part1(input: List<String>): Int {
        return input.map { it.splitInts() }.count(::checkGood)
    }

    fun part2(input: List<String>): Int {
        val ilist = input.map { it.splitInts() }
        var sum = 0
        for (i in ilist) {
            for (dp in ilist.indices) {
                if (checkGood(i.filterIndexed { index, _ -> dp != index })) {
                    sum++
                    break
                }
            }
        }
        return sum
    }

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

    val input = readInput("aoc2024/Day02")
    part1(input).println()
    part2(input).println()
}
