File tree Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Original file line number Diff line number Diff line change 1- package com.github.micheljung.adventofcode.y2024
1+ package com.github.micheljung.adventofcode.y2023
22
33import com.github.micheljung.adventofcode.common.Solver
44
Original file line number Diff line number Diff line change 11package com.github.micheljung.adventofcode.y2024
22
33import com.github.micheljung.adventofcode.common.Solver
4+ import kotlin.math.abs
45
56object 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}
You can’t perform that action at this time.
0 commit comments