day(04): solve
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
d7b0d5adf1
commit
5df8cfcf75
2 changed files with 76 additions and 0 deletions
10
inputs/day04/sample.txt
Normal file
10
inputs/day04/sample.txt
Normal file
|
@ -0,0 +1,10 @@
|
|||
MMMSXXMASM
|
||||
MSAMXMSMSA
|
||||
AMXSXMAAMM
|
||||
MSAMASMSMX
|
||||
XMASAMXAMM
|
||||
XXAMMXXAMA
|
||||
SMSMSASXSS
|
||||
SAXAMASAAA
|
||||
MAMMMXMMMM
|
||||
MXMXAXMASX
|
66
src/Day04.kt
Normal file
66
src/Day04.kt
Normal file
|
@ -0,0 +1,66 @@
|
|||
class Day04(
|
||||
inputType: String,
|
||||
) : Day<Int, Int>() {
|
||||
private val wordSearch: List<String> = readInput(4, inputType)
|
||||
|
||||
companion object {
|
||||
private val DIRECTIONS = product(-1..1, -1..1).filter { (x, y) -> x != 0 || y != 0 }
|
||||
}
|
||||
|
||||
override fun precompute() {
|
||||
// no-op
|
||||
}
|
||||
|
||||
private fun checkForXmas(
|
||||
y0: Int,
|
||||
x0: Int,
|
||||
dy: Int,
|
||||
dx: Int,
|
||||
): Boolean =
|
||||
"XMAS".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 part1(): Int =
|
||||
product(wordSearch.indices, wordSearch[0].indices).sumOf { (y, x) ->
|
||||
DIRECTIONS.count { (dy, dx) ->
|
||||
checkForXmas(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 =
|
||||
product(wordSearch.indices, wordSearch[0].indices).sumOf { (y, x) ->
|
||||
when (wordSearch[y][x]) {
|
||||
'A' ->
|
||||
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),
|
||||
).count { (d0, d1) ->
|
||||
val (dy0, dx0) = d0
|
||||
val (dy1, dx1) = d1
|
||||
checkForMas(y - dy0, x - dx0, dy0, dx0) && checkForMas(y - dy1, x - dx1, dy1, dx1)
|
||||
}
|
||||
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun main() {
|
||||
Day04("sample").test(18, 9)
|
||||
Day04("input").run()
|
||||
}
|
Loading…
Reference in a new issue