From e69277a731c7cb0866d9084acf2466f3a257f738 Mon Sep 17 00:00:00 2001 From: Sven Weidauer Date: Wed, 1 Jan 2025 12:21:30 +0100 Subject: [PATCH] WIP day 21 --- 2024/src/main/kotlin/CharGrid.kt | 2 + 2024/src/main/kotlin/day21.kt | 63 ++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 2024/src/main/kotlin/day21.kt diff --git a/2024/src/main/kotlin/CharGrid.kt b/2024/src/main/kotlin/CharGrid.kt index 8a32f66..9447750 100644 --- a/2024/src/main/kotlin/CharGrid.kt +++ b/2024/src/main/kotlin/CharGrid.kt @@ -6,6 +6,8 @@ class CharGrid(rows: List) : Grid { constructor(width: Int, height: Int, char: Char) : this((1..height).map { char.toString().repeat(width) }) + constructor(vararg rows: String) : this(rows.toList()) + init { assert(rows.all { it.length == width }) } diff --git a/2024/src/main/kotlin/day21.kt b/2024/src/main/kotlin/day21.kt new file mode 100644 index 0000000..b598448 --- /dev/null +++ b/2024/src/main/kotlin/day21.kt @@ -0,0 +1,63 @@ +fun main() { + val inputs = listOf( + "789A", + "540A", + "285A", + "140A", + "189A", + ) + + val numberPad = CharGrid( + "789", + "456", + "123", + " 0A" + ) + + val robotPad = CharGrid( + " ^A", + "" + ) + + println(keySequence("029A", numberPad)) + println(keySequence(keySequence("029A", numberPad), robotPad)) + Integer.parseInt() + println("029A".toInt()) + +} + +fun keySequence(code: String, pad: CharGrid, start: Char = 'A'): String { + var position = pad.find(start) ?: error("Start position not found") + val gap = pad.find(' ') ?: error("Gap not found") + + val result = StringBuilder() + for (current in code) { + val target = pad.find(current) ?: error("Target key not found") + + val dx = target.x - position.x + val dy = target.y - position.y + + if (target.y < gap.y) { + result.appendMovement(dy, '^', 'v') + result.appendMovement(dx, '<', '>') + } else { + result.appendMovement(dx, '<', '>') + result.appendMovement(dy, '^', 'v') + } + + result.append('A') + + position = target + } + + return result.toString() +} + +fun StringBuilder.appendMovement(amount: Int, less: Char, more: Char): StringBuilder { + when { + amount < 0 -> repeat(-amount) { append(less) } + amount == 0 -> Unit + else -> repeat(amount) { append(more) } + } + return this +} \ No newline at end of file