Skip to content

Commit c8b0c78

Browse files
Solve 2024-2
1 parent cab01ef commit c8b0c78

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

y2023/src/main/kotlin/Day2Solver.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.github.micheljung.adventofcode.y2024
1+
package com.github.micheljung.adventofcode.y2023
22

33
import com.github.micheljung.adventofcode.common.Solver
44

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,51 @@
11
package com.github.micheljung.adventofcode.y2024
22

33
import com.github.micheljung.adventofcode.common.Solver
4+
import kotlin.math.abs
45

56
object Day2Solver : Solver {
7+
68
override fun solve(sequence: Sequence<String>): String {
7-
TODO("Not yet implemented")
9+
val list = sequence.toList()
10+
val part1 = list
11+
.map { it.split(" ").map(String::toInt) }
12+
.associateWith { isSafe(it) }
13+
.values
14+
.count { it }
15+
.toString()
16+
17+
val part2 = list
18+
.map { it.split(" ").map(String::toInt) }
19+
.count { isSafeWithDampener(it) }
20+
.toString()
21+
22+
return "$part1, $part2"
23+
}
24+
25+
private fun isSafeWithDampener(ints: List<Int>): Boolean {
26+
var index = 0
27+
return ints.any {
28+
val dampened = mutableListOf(*ints.toTypedArray()).apply {
29+
removeAt(index++)
30+
}
31+
isSafe(dampened)
32+
}
33+
}
34+
35+
private fun isSafe(ints: List<Int>): Boolean {
36+
var isLineIncreasing: Boolean? = null
37+
for ((current, previous) in ints.windowed(2)) {
38+
val isWithinDistance = abs(current - previous) in 1..3
39+
if (!isWithinDistance) return false
40+
41+
val isCurrentIncreasing = current > previous
42+
if (isLineIncreasing == null) isLineIncreasing = isCurrentIncreasing
43+
when {
44+
isLineIncreasing && !isCurrentIncreasing -> return false
45+
!isLineIncreasing && isCurrentIncreasing -> return false
46+
}
47+
}
48+
49+
return true
850
}
951
}

0 commit comments

Comments
 (0)