Skip to content

Commit

Permalink
2024 day 01
Browse files Browse the repository at this point in the history
  • Loading branch information
markjfisher committed Dec 1, 2024
1 parent 1347b18 commit f22cb81
Show file tree
Hide file tree
Showing 8 changed files with 1,100 additions and 1 deletion.
15 changes: 15 additions & 0 deletions advents/src/main/kotlin/net/fish/y2024/AdventOfCode.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
@file:JvmName("AdventOfCode2024")
package net.fish.y2024

import net.fish.Reflect
import net.fish.Runner

object AdventOfCode {
val days = Reflect.getDays(2024)
}

fun main(args: Array<String>) {
// WindowsAnsi.setup()
val day = if(args.isEmpty()) 0 else args[0].toInt()
Runner.run(2024, AdventOfCode.days, day)
}
35 changes: 35 additions & 0 deletions advents/src/main/kotlin/net/fish/y2024/Day01.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package net.fish.y2024

import kotlin.math.abs
import net.fish.Day
import net.fish.resourceLines

object Day01 : Day {
private val data by lazy {
linesToLists(resourceLines(2024, 1))
}

override fun part1() = doPart1(data)
override fun part2() = doPart2(data)

fun doPart1(data: Pair<List<Int>, List<Int>>): Int = (data.first zip data.second).sumOf { (a, b) -> abs(a - b) }

fun doPart2(data: Pair<List<Int>, List<Int>>): Int {
val frequencies = data.second.groupingBy { it }.eachCount()
return data.first.sumOf { it * frequencies.getOrDefault(it, 0) }
}

private fun splitLine(line: String): Pair<Int, Int> = line.split(" ", limit = 2).map(String::toInt).let { (x, y) -> Pair(x, y) }

fun linesToLists(lines: List<String>): Pair<List<Int>, List<Int>> = lines
.map { splitLine(it) }
.fold(Pair(emptyList<Int>(), emptyList<Int>())) { acc, current ->
Pair(acc.first + current.first, acc.second + current.second)
}.let { (l1, l2) -> Pair(l1.sorted(), l2.sorted()) }

@JvmStatic
fun main(args: Array<String>) {
println(part1())
println(part2())
}
}
Loading

0 comments on commit f22cb81

Please sign in to comment.