Skip to content

Commit

Permalink
Solve Day 2
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulWoitaschek committed Dec 2, 2024
1 parent a3bac6f commit e4d9dcc
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
28 changes: 28 additions & 0 deletions 2024/src/main/kotlin/aoc/year2024/Day2.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package aoc.year2024

import aoc.library.Puzzle
import kotlin.math.absoluteValue

object Day2 : Puzzle<Int, Int>(day = 2) {

override fun solvePart1(input: String): Int = parse(input).count { reportIsSafe(it) }

override fun solvePart2(input: String): Int = parse(input)
.count { report ->
report.indices.any { removeIndex ->
val adjustedReport = report.toMutableList()
.apply { removeAt(removeIndex) }
reportIsSafe(adjustedReport)
}
}

private fun reportIsSafe(report: List<Int>): Boolean {
val steps = report.windowed(2).map { it[1] - it[0] }
val monotonic = steps.all { it > 0 } || steps.all { it < 0 }
return monotonic && steps.all { it.absoluteValue in 1..3 }
}

private fun parse(input: String): List<List<Int>> = input.lines().map {
it.split(" ").map(String::toInt)
}
}
38 changes: 38 additions & 0 deletions 2024/src/test/kotlin/aoc/year2024/Day2Test.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package aoc.year2024

import aoc.library.solvePart1
import aoc.library.solvePart2
import io.kotest.matchers.ints.shouldBeExactly
import org.junit.jupiter.api.Test

class Day2Test {

private val testInput = """
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9
""".trimIndent()

@Test
fun part1TestInput() {
Day2.solvePart1(testInput) shouldBeExactly 2
}

@Test
fun part1() {
Day2.solvePart1() shouldBeExactly 341
}

@Test
fun part2TestInput() {
Day2.solvePart2(testInput) shouldBeExactly 4
}

@Test
fun part2() {
Day2.solvePart2() shouldBeExactly 404
}
}

0 comments on commit e4d9dcc

Please sign in to comment.