-
Notifications
You must be signed in to change notification settings - Fork 4
/
Day5.kt
47 lines (42 loc) · 1.54 KB
/
Day5.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.github.ephemient.aoc2022
@Day
class Day5(lines: List<String>) {
private val initialStacks: Map<Char, String>
private val moves: List<Triple<Int, Char, Char>>
init {
val n = lines.indexOf("")
initialStacks = buildMap {
lines[n - 1].forEachIndexed { i, c ->
if (!c.isDigit()) return@forEachIndexed
for (j in 0 until n) {
if (lines[j].getOrNull(i)?.isWhitespace() == false) {
put(c, buildString(n - 1 - j) { for (k in j until n - 1) append(lines[k][i]) })
break
}
}
}
}
moves = buildList(lines.size - n - 1) {
for (i in n + 1 until lines.size) {
val (num, x, y) = PATTERN.matchEntire(lines[i])!!.destructured
add(Triple(num.toInt(), x.single(), y.single()))
}
}
}
@Day.Part
fun part1(): String = solve(true)
@Day.Part
fun part2(): String = solve(false)
private fun solve(reverse: Boolean): String {
val stacks = initialStacks.toMutableMap()
for ((num, x, y) in moves) {
val source = stacks.getValue(x)
stacks[x] = source.drop(num)
stacks[y] = (if (reverse) source.take(num).reversed() else source.take(num)) + stacks.getValue(y)
}
return stacks.values.joinToString("") { it[0].toString() }
}
companion object {
private val PATTERN = """move (\d+) from (\d) to (\d)""".toRegex()
}
}