package aoc2024

import println
import readInput
import splitInts
import kotlin.math.abs

/*
--- Day 1: Historian Hysteria ---
https://adventofcode.com/2024/day/1
*/
fun main() {

    val inlineTestInput = """
3   4
4   3
2   5
1   3
3   9
3   3
"""

    fun part1(input: List<String>): Int {
        val left = ArrayList<Int>()
        val right = ArrayList<Int>()
        for (i in input) {
            val (l, r) = i.splitInts()
            left.add(l)
            right.add(r)
        }
        left.sort()
        right.sort()
        return left.zip(right).sumOf { abs(it.first - it.second) }
    }

    fun part2(input: List<String>): Int {
        val left = ArrayList<Int>()
        val right = ArrayList<Int>()
        for (i in input) {
            val (l, r) = i.splitInts()
            left.add(l)
            right.add(r)
        }
        val grouped = right.groupBy { it }
        return left.sumOf { it * (grouped[it]?.size ?: 0) }
    }

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

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