Skip to content

Instantly share code, notes, and snippets.

@bartoszm
Last active December 10, 2021 06:34
Show Gist options
  • Save bartoszm/ce5d1b7d278b2ced811d3198e00ea1df to your computer and use it in GitHub Desktop.
Save bartoszm/ce5d1b7d278b2ced811d3198e00ea1df to your computer and use it in GitHub Desktop.
Day 10 part 2
package day10
import java.nio.file.Files
import java.nio.file.Path
import kotlin.system.measureTimeMillis
object Day10b {
val mapScore = mapOf(
')' to 1L,
']' to 2L,
'}' to 3L,
'>' to 4L,
)
val matching = mapOf(
')' to '(',
']' to '[',
'}' to '{',
'>' to '<',
)
val reversed by lazy { matching.entries.associateBy({ it.value }) { it.key } }
fun solve(inputs: List<String>): Long {
val scores = inputs
.map { solver(it.toList()) }
.filter { it.first == null && it.second.isNotEmpty() }
.map { complete(it.second) }
.map { score(it) }
.sorted()
return scores[scores.size / 2]
}
private fun score(chars: List<Char>) = chars.map { mapScore[it] ?: 0 }.reduce{res, x -> res * 5 + x }
private fun complete(stack: List<Char>) = stack.map { reversed[it] }.filterNotNull()
private fun solver(chars: List<Char>): Pair<Char?, List<Char>> {
val stack = ArrayDeque<Char>()
for(c in chars) {
if(c in matching.keys) {
if(stack.isEmpty()) {
return Pair(c, listOf())
}
val first = stack.removeFirst()
if(first != matching[c]) {
return Pair(c, stack)
}
} else {
stack.addFirst(c)
}
}
return Pair(null, stack)
}
}
fun main(args: Array<String>) {
val inputs = Files.readAllLines(Path.of(args[0]))
val result: Long
val timeMs = measureTimeMillis {
result = Day10b.solve(inputs)
}
println(result)
println("$timeMs ms")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment