From 5df8cfcf753108b5e874dac632e9e03684ff76f5 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 4 Dec 2024 11:32:14 +0100 Subject: [PATCH] day(04): solve Signed-off-by: Matej Focko --- inputs/day04/sample.txt | 10 +++++++ src/Day04.kt | 66 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 inputs/day04/sample.txt create mode 100644 src/Day04.kt diff --git a/inputs/day04/sample.txt b/inputs/day04/sample.txt new file mode 100644 index 0000000..c41c5ea --- /dev/null +++ b/inputs/day04/sample.txt @@ -0,0 +1,10 @@ +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX \ No newline at end of file diff --git a/src/Day04.kt b/src/Day04.kt new file mode 100644 index 0000000..5762456 --- /dev/null +++ b/src/Day04.kt @@ -0,0 +1,66 @@ +class Day04( + inputType: String, +) : Day() { + private val wordSearch: List = 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() +}