package aoc2023

import println
import readInput
import splitInts

/*
--- Day 9: Mirage Maintenance ---
https://adventofcode.com/2023/day/9
*/
fun main() {

    val inlineTestInput = """
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
"""

    fun delta(i: List<Int>): Int {
        if (i.all { it == 0 }) return 0
        val d = i.zipWithNext { a, b -> b - a }
        return d.last() + delta(d)
    }

    fun delta2(i: List<Int>): Int {
        if (i.all { it == 0 }) return 0
        val d = i.zipWithNext { a, b -> b - a }
        return d.first() - delta2(d)
    }

    fun part1(input: List<String>): Int {
        return input.map { it.splitInts() }.sumOf { delta(it) + it.last() }
    }

    fun part2(input: List<String>): Int {
        return input.map { it.splitInts() }.sumOf { it.first() - delta2(it) }
    }

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

    val input = readInput("aoc2023/Day09")
    part1(input).println()
    part2(input).println()
}
