Skip to content

Commit 3a2b2ed

Browse files
committed
Day 2
1 parent 03465c0 commit 3a2b2ed

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

src/main/kotlin/y24/Day2.kt

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package y24
2+
3+
import common.puzzle.solvePuzzle
4+
import common.puzzle.Input
5+
import common.puzzle.Puzzle
6+
import common.puzzle.splitToInts
7+
import kotlin.math.*
8+
9+
fun main() = solvePuzzle(year = 2024, day = 2) { Day2(it) }
10+
11+
class Day2(val input: Input) : Puzzle {
12+
13+
override fun solveLevel1(): Any {
14+
return input.lines.count {
15+
isSafe(it.splitToInts(" "), 0, 1)
16+
}
17+
}
18+
19+
private fun isSafe(level: List<Int>, i0: Int, i1: Int, skipIndex: Int = level.size): Boolean {
20+
if (i1 >= level.size || (i1 >= skipIndex && i1 + 1 >= level.size)) {
21+
return true
22+
}
23+
24+
val first = if (skipIndex == 0) 1 else 0
25+
val second = if (skipIndex <= 1) 2 else 1
26+
val sign = (level[second] - level[first]).sign
27+
28+
val v0 = if (i0 >= skipIndex) level[i0 + 1] else level[i0]
29+
val v1 = if (i1 >= skipIndex) level[i1 + 1] else level[i1]
30+
31+
if (areValuesSafe(sign, v0, v1)) {
32+
return isSafe(level, i0 + 1, i1 + 1, skipIndex)
33+
}
34+
35+
return false
36+
}
37+
38+
private fun areValuesSafe(sign: Int, val0: Int, val1: Int): Boolean {
39+
val diff = abs(val1 - val0)
40+
if (diff == 0 || diff > 3) {
41+
return false
42+
}
43+
return (val1 - val0).sign == sign
44+
}
45+
46+
override fun solveLevel2(): Any {
47+
return input.lines.count {
48+
val report = it.splitToInts(" ")
49+
50+
// Try skipping each index, or not skipping at all (index = report.size).
51+
(0..report.size).any { skipIndex ->
52+
isSafe(report, 0, 1, skipIndex)
53+
}
54+
}
55+
}
56+
}

src/test/kotlin/y24/Day2Test.kt

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package y24
2+
3+
import common.puzzle.Input
4+
import org.junit.jupiter.api.Assertions.assertEquals
5+
import org.junit.jupiter.api.Test
6+
7+
internal class Day2Test {
8+
private val sample = Input("""
9+
7 6 4 2 1
10+
1 2 7 8 9
11+
9 7 6 2 1
12+
1 3 2 4 5
13+
8 6 4 4 1
14+
1 3 6 7 9
15+
""".trimIndent())
16+
17+
private val day = Day2(sample)
18+
19+
@Test
20+
fun solveLevel1() {
21+
assertEquals(2, day.solveLevel1())
22+
}
23+
24+
@Test
25+
fun solveLevel2() {
26+
assertEquals(4, day.solveLevel2())
27+
28+
assertEquals(1, Day2(Input("29 32 30 31 34 35 37")).solveLevel2())
29+
assertEquals(1, Day2(Input("27 25 26 27 30 31")).solveLevel2())
30+
}
31+
}

0 commit comments

Comments
 (0)