From cb8880e3a703f5a59c7b14b41f39b1016b83fe78 Mon Sep 17 00:00:00 2001 From: "Mohsen.Biglari" Date: Wed, 4 Dec 2024 16:37:42 +0100 Subject: [PATCH] Day 4 --- src/Day04.kt | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 src/Day04.kt diff --git a/src/Day04.kt b/src/Day04.kt new file mode 100644 index 0000000..76940dd --- /dev/null +++ b/src/Day04.kt @@ -0,0 +1,84 @@ +import Direction.* + +enum class Direction(val x: Int, val y: Int) { + Left(-1, 0), Right(1, 0), Up(0, -1), Down(0, 1), + RightDown(1, 1), RightUp(1, -1), LeftDown(-1, 1), LeftUp(-1, -1) +} + +fun main() { + + data class Point(val row: Int, val col: Int) { + fun move(direction: Direction) = this.copy(row = row + direction.y, col = col + direction.x) + } + + class CharTable( + private val table: Array, + ) { + constructor(list: List) : this(list.map { it.toCharArray() }.toTypedArray()) + + val size = table.size + + fun get(point: Point): Char? { + if (point.row in table.indices) { + if (point.col in table[point.row].indices) { + return table[point.row][point.col] + } + } + return null + } + } + + fun findMas(table: CharTable, curr: Point, direction: Direction, sequence: String = ""): Boolean { + val currChar = table.get(curr) ?: return false + val word = sequence + currChar + if (word.contentEquals("MAS")) return true + if ("MAS".startsWith(word)) return findMas(table, curr.move(direction), direction, word) + return false + } + + fun findStarShapeMas(table: CharTable, curr: Point): Boolean { + val currChar = table.get(curr) ?: return false + if (currChar == 'A') { + // Check if this is the center of a star + val firstDiagonal = findMas(table, curr.move(LeftUp), RightDown) || findMas(table, curr.move(RightDown), LeftUp) + val secondDiagonal = findMas(table, curr.move(RightUp), LeftDown) || findMas(table, curr.move(LeftDown), RightUp) + return firstDiagonal && secondDiagonal + } + return false + } + + fun part1(input: List): Int { + val table = CharTable(input) + var count = 0 + for (row in 0..): Int { + val table = CharTable(input) + var count = 0 + for (row in 0..