day(04): factor out crossing directions

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

View file

@ -5,6 +5,13 @@ class Day04(
companion object { companion object {
private val DIRECTIONS = product(-1..1, -1..1).filter { (x, y) -> x != 0 || y != 0 } private val DIRECTIONS = product(-1..1, -1..1).filter { (x, y) -> x != 0 || y != 0 }
private val NEIGHBORING_DIRECTIONS =
listOf(
(1 to 1) to (1 to -1),
(1 to -1) to (-1 to -1),
(-1 to -1) to (-1 to 1),
(-1 to 1) to (1 to 1),
)
} }
override fun precompute() { override fun precompute() {
@ -34,12 +41,7 @@ class Day04(
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]) {
'A' -> 'A' ->
listOf( NEIGHBORING_DIRECTIONS.count { (d0, d1) ->
(1 to 1) to (1 to -1),
(1 to -1) to (-1 to -1),
(-1 to -1) to (-1 to 1),
(-1 to 1) to (1 to 1),
).count { (d0, d1) ->
val (dy0, dx0) = d0 val (dy0, dx0) = d0
val (dy1, dx1) = d1 val (dy1, dx1) = d1
startsWith("MAS", y - dy0, x - dx0, dy0, dx0) && startsWith("MAS", y - dy1, x - dx1, dy1, dx1) startsWith("MAS", y - dy0, x - dx0, dy0, dx0) && startsWith("MAS", y - dy1, x - dx1, dy1, dx1)