day(04): use one helper function for both parts

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-04 11:34:57 +01:00
parent 5df8cfcf75
commit cecb4e9c30
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -11,13 +11,14 @@ class Day04(
// no-op // no-op
} }
private fun checkForXmas( private fun startsWith(
word: String,
y0: Int, y0: Int,
x0: Int, x0: Int,
dy: Int, dy: Int,
dx: Int, dx: Int,
): Boolean = ): Boolean =
"XMAS".withIndex().all { c -> word.withIndex().all { c ->
val (y, x) = y0 + dy * c.index to x0 + dx * c.index val (y, x) = y0 + dy * c.index to x0 + dx * c.index
y in wordSearch.indices && x in wordSearch[y].indices && wordSearch[y][x] == c.value y in wordSearch.indices && x in wordSearch[y].indices && wordSearch[y][x] == c.value
} }
@ -25,21 +26,10 @@ class Day04(
override fun part1(): Int = override fun part1(): Int =
product(wordSearch.indices, wordSearch[0].indices).sumOf { (y, x) -> product(wordSearch.indices, wordSearch[0].indices).sumOf { (y, x) ->
DIRECTIONS.count { (dy, dx) -> DIRECTIONS.count { (dy, dx) ->
checkForXmas(y, x, dy, dx) startsWith("XMAS", y, x, dy, dx)
} }
} }
private fun checkForMas(
y0: Int,
x0: Int,
dy: Int,
dx: Int,
): Boolean =
"MAS".withIndex().all { c ->
val (y, x) = y0 + dy * c.index to x0 + dx * c.index
y in wordSearch.indices && x in wordSearch[y].indices && wordSearch[y][x] == c.value
}
override fun part2(): Int = override fun part2(): Int =
product(wordSearch.indices, wordSearch[0].indices).sumOf { (y, x) -> product(wordSearch.indices, wordSearch[0].indices).sumOf { (y, x) ->
when (wordSearch[y][x]) { when (wordSearch[y][x]) {
@ -52,7 +42,7 @@ class Day04(
).count { (d0, d1) -> ).count { (d0, d1) ->
val (dy0, dx0) = d0 val (dy0, dx0) = d0
val (dy1, dx1) = d1 val (dy1, dx1) = d1
checkForMas(y - dy0, x - dx0, dy0, dx0) && checkForMas(y - dy1, x - dx1, dy1, dx1) startsWith("MAS", y - dy0, x - dx0, dy0, dx0) && startsWith("MAS", y - dy1, x - dx1, dy1, dx1)
} }
else -> 0 else -> 0