-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #26 from ephemient/kt/day3
- Loading branch information
Showing
1 changed file
with
8 additions
and
23 deletions.
There are no files selected for viewing
31 changes: 8 additions & 23 deletions
31
kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day3.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,16 @@ | ||
package com.github.ephemient.aoc2024 | ||
|
||
class Day3(private val input: String) { | ||
fun part1(): Int = regex1.findAll(input).sumOf { match -> | ||
val (x, y) = match.destructured | ||
x.toInt() * y.toInt() | ||
} | ||
fun part1(): Int = part1(input) | ||
|
||
fun part2(): Int { | ||
var enable = true | ||
return regex2.findAll(input) | ||
.filter { match -> | ||
val (yes, no) = match.destructured | ||
enable = when { | ||
yes.isNotEmpty() -> true | ||
no.isNotEmpty() -> false | ||
else -> return@filter enable | ||
} | ||
false | ||
} | ||
.sumOf { match -> | ||
val (_, _, x, y) = match.destructured | ||
x.toInt() * y.toInt() | ||
} | ||
} | ||
fun part2(): Int = input.splitToSequence("do()").sumOf { part1(it.substringBefore("don't()")) } | ||
|
||
companion object { | ||
private val regex1 = """mul\((\d+),(\d+)\)""".toRegex() | ||
private val regex2 = """(do\(\))|(don't\(\))|mul\((\d+),(\d+)\)""".toRegex() | ||
private val regex = """mul\((\d+),(\d+)\)""".toRegex() | ||
|
||
private fun part1(input: String): Int = regex.findAll(input).sumOf { match -> | ||
val (x, y) = match.destructured | ||
x.toInt() * y.toInt() | ||
} | ||
} | ||
} |