Day 2 part 1 + beginning of part 2

This commit is contained in:
Sven Weidauer 2024-12-02 22:07:22 +01:00
parent 7d8dc6bc82
commit f6425f1d56
5 changed files with 1039 additions and 5 deletions

2
2024/.idea/vcs.xml generated
View file

@ -2,6 +2,6 @@
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
<mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View file

@ -0,0 +1,4 @@
fun readInput(name: String) = object {}.javaClass.getResourceAsStream(name)
?.bufferedReader()
?.lineSequence()
?: error("Cannot read input")

View file

@ -1,10 +1,7 @@
import kotlin.math.abs
fun main() {
val input = object {}.javaClass.getResourceAsStream("day1.txt")
?.bufferedReader()
?.lineSequence()
?: error("Cannot read input")
val input = readInput("day1.txt")
val a = mutableListOf<Int>()
val b = mutableListOf<Int>()

View file

@ -0,0 +1,33 @@
import kotlin.math.abs
fun main() {
val input = readInput("day2.txt")
.map { line -> line.split(" ").map { it.toInt() } }
val safe = input.count { isSafe(it) }
println("Part 1: $safe")
}
private fun isSafe(report: List<Int>): Boolean {
data class State(val increasing: Boolean? = null, val last: Int? = null, val safe: Boolean = true, val usedProblemDampener: Boolean = false) {
fun update(next: Int): State = when {
!safe -> this
last == null -> copy(last = next)
increasing == null -> copy(increasing = last < next, last = next, safe = safeIncrement(last, next))
increasing -> copy(last = next, safe = safeIncrement(last, next) && last < next)
else -> copy(last = next, safe = safeIncrement(last, next) && last > next)
}.problemDampener()
fun safeIncrement(last: Int, next: Int): Boolean = abs(last - next) in 1..3
fun problemDampener() = when {
!safe && !usedProblemDampener -> copy(safe = true, usedProblemDampener = true)
else -> this
}
}
return report.fold(State()) { state, next ->
state.update(next)
.also { if (!it.safe) return@fold it }
}.safe
}

File diff suppressed because it is too large Load diff