Day 2 part 1 + beginning of part 2
This commit is contained in:
parent
7d8dc6bc82
commit
f6425f1d56
5 changed files with 1039 additions and 5 deletions
2
2024/.idea/vcs.xml
generated
2
2024/.idea/vcs.xml
generated
|
@ -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>
|
4
2024/src/main/kotlin/Utils.kt
Normal file
4
2024/src/main/kotlin/Utils.kt
Normal file
|
@ -0,0 +1,4 @@
|
|||
fun readInput(name: String) = object {}.javaClass.getResourceAsStream(name)
|
||||
?.bufferedReader()
|
||||
?.lineSequence()
|
||||
?: error("Cannot read input")
|
|
@ -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>()
|
||||
|
|
33
2024/src/main/kotlin/day2.kt
Normal file
33
2024/src/main/kotlin/day2.kt
Normal 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
|
||||
}
|
1000
2024/src/main/resources/day2.txt
Normal file
1000
2024/src/main/resources/day2.txt
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Reference in a new issue