From 6e18c4a72d8e5e8cbeae06060d249f7d6bf6a768 Mon Sep 17 00:00:00 2001 From: Sven Weidauer Date: Sat, 7 Dec 2024 22:12:44 +0100 Subject: [PATCH] Day 4 Part 2 --- 2024/src/main/kotlin/day4.kt | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/2024/src/main/kotlin/day4.kt b/2024/src/main/kotlin/day4.kt index f340b87..19aa5b9 100644 --- a/2024/src/main/kotlin/day4.kt +++ b/2024/src/main/kotlin/day4.kt @@ -3,12 +3,33 @@ fun main() { val part1 = grid.all().fold(0) { acc, line -> val string = line.joinToString(separator = "") - println(string) - acc + string.countSubstring("XMAS") + string.countSubstring("SAMX") } println("Part 1: $part1") + + var part2 = 0 + for (y in 1..<(grid.height - 1)) { + val row = grid.rows[y] + part2 += row.indices.filter { it > 0 && it < grid.width - 1 && row[it] == 'A' } + .count { grid.xmasAt(it, y) } + } + println("Part 2: $part2") + +} + +fun Grid.xmasAt(x: Int, y: Int): Boolean { + assert(get(x, y) == 'A') + + val tl = get(x - 1, y - 1) + val tr = get(x + 1, y - 1) + val bl = get(x - 1, y + 1) + val br = get(x + 1, y + 1) + + val d1 = (tl == 'M' && br == 'S') || (tl == 'S' && br == 'M') + val d2 = (bl == 'M' && tr == 'S') || (bl == 'S' && tr == 'M') + + return d1 && d2 } fun String.countSubstring(substring: String): Int {