Skip to content

Commit

Permalink
2024 Day 03 Part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
fmmr committed Dec 3, 2024
1 parent d26212b commit 9d93c33
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 14 deletions.
40 changes: 29 additions & 11 deletions src/main/kotlin/no/rodland/advent_2024/Day03.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,44 @@ import no.rodland.advent.Day
// template generated: 03/12/2024
// Fredrik Rødland 2024

class Day03(val input: List<String>) : Day<Long, Long, List<Pair<Int, Int>>> {
private val multRegEx = "mul\\((\\d{1,3}),(\\d{1,3})\\)".toRegex()
class Day03(val input: List<String>) : Day<Long, Long, List<String>> {
private val multRegEx = """mul\((\d{1,3}),(\d{1,3})\)""".toRegex()

private val parsed = input.parse()

override fun partOne(): Long {
return parsed.sumOf { (a, b) -> a * b }.toLong()
return parsed
.flatMap { line ->
multRegEx.findAll(line).toList().map { mr ->
mr.groupValues[1].toInt() * mr.groupValues[2].toInt()
}
}
.sum()
.toLong()
}

override fun partTwo(): Long {
return 2
}

override fun List<String>.parse(): List<Pair<Int, Int>> {
return flatMap { line ->
multRegEx.findAll(line).toList().map { mr ->
mr.groupValues[1].toInt() to mr.groupValues[2].toInt()
val matches = """mul\((\d{1,3}),(\d{1,3})\)|do\(\)|don't\(\)""".toRegex()
var inDoMode = true
return parsed
.flatMap { line ->
sequence {
matches
.findAll(line)
.forEach { mr ->
when {
mr.value == "do()" -> inDoMode = true
mr.value == "don't()" -> inDoMode = false
multRegEx.matches(mr.value) && inDoMode -> yield(mr.groupValues[1].toInt() * mr.groupValues[2].toInt())
}
}
}
}
}
.sum()
.toLong()
}

override fun List<String>.parse(): List<String> = this

override val day = "03".toInt()
}
4 changes: 2 additions & 2 deletions src/test/kotlin/no/rodland/advent_2024/Day03Test.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ internal class Day03Test {
private val test03 = "2024/input_03_test.txt".readFile()

private val resultTestOne = 161L
private val resultTestTwo = 2L
private val resultTestTwo = 48L
private val resultOne = 187825547L
private val resultTwo = 2L
private val resultTwo = 85508223L

val test = defaultTestSuiteParseOnInit(
Day03(data03),
Expand Down
2 changes: 1 addition & 1 deletion src/test/resources/2024/input_03_test.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))

0 comments on commit 9d93c33

Please sign in to comment.