1
0
Fork 0

day(10): reformat and refactor

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2021-12-10 06:42:35 +01:00
parent 91e5a765ec
commit 5a2ca59ee1

View file

@ -3,62 +3,47 @@ package year2021.day10
import readInput import readInput
val CLOSING: Map<Char, Char> = mapOf( val CLOSING: Map<Char, Char> = mapOf(
')' to '(', ')' to '(', ']' to '[', '}' to '{', '>' to '<'
']' to '[', )
'}' to '{', val ERROR_SCORING: Map<Char, Int> = mapOf(
'>' to '<' ')' to 3, ']' to 57, '}' to 1197, '>' to 25137
) )
val ERROR_SCORING: Map<Char, Int> = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137)
val AUTOCOMPLETE_SCORING: Map<Char, Long> = mapOf( val AUTOCOMPLETE_SCORING: Map<Char, Long> = mapOf(
'(' to 1, '(' to 1, '[' to 2, '{' to 3, '<' to 4
'[' to 2,
'{' to 3,
'<' to 4
) )
fun firstInvalid(input: String): Char? { fun check(input: String): Pair<Char?, List<Char>> {
val stack = mutableListOf<Char>() val stack = mutableListOf<Char>()
for (c in input) { for (c in input) {
if (CLOSING.contains(c)) { if (CLOSING.contains(c)) {
// found a closing one // found a closing one
if (stack.size < 1 || stack.last() != CLOSING[c]) { if (stack.size < 1 || stack.last() != CLOSING[c]) {
return c return Pair(c, stack)
} }
stack.removeLast() stack.removeLast()
} else { } else {
stack.add(c) stack.add(c)
} }
} }
return null return Pair(null, stack)
} }
fun part1(input: List<String>): Int = input.sumOf { fun part1(input: List<String>): Int = input.sumOf {
firstInvalid(it)?.let { c -> check(it).let { (c, _) ->
ERROR_SCORING[c] ERROR_SCORING.getOrDefault(c, 0)
} ?: 0
}
fun getRemaining(input: String): List<Char> {
val stack = mutableListOf<Char>()
for (c in input) {
if (CLOSING.contains(c)) {
stack.removeLast()
} else {
stack.add(c)
} }
} }
return stack fun part2(input: List<String>): Long =
input
.map { check(it) }
.filter { (c, s) -> c == null && s.isNotEmpty() }
.map { (_, stack) ->
stack.reversed().fold(0.toLong()) { total, c ->
5 * total + AUTOCOMPLETE_SCORING[c]!!
} }
}.sorted().let { scores ->
fun part2(input: List<String>): Long = input
.filter { firstInvalid(it) == null }
.map {
getRemaining(it).reversed().fold(0.toLong()) { total, c -> 5 * total + AUTOCOMPLETE_SCORING[c]!! }
}
.sorted().let { scores ->
scores[scores.size / 2] scores[scores.size / 2]
} }