From 5a2ca59ee1852411387ad28051d1520c24dab771 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 10 Dec 2021 06:42:35 +0100 Subject: [PATCH] day(10): reformat and refactor Signed-off-by: Matej Focko --- src/year2021/day10/Day10.kt | 57 ++++++++++++++----------------------- 1 file changed, 21 insertions(+), 36 deletions(-) diff --git a/src/year2021/day10/Day10.kt b/src/year2021/day10/Day10.kt index ead3a24..291c4c8 100644 --- a/src/year2021/day10/Day10.kt +++ b/src/year2021/day10/Day10.kt @@ -3,64 +3,49 @@ package year2021.day10 import readInput val CLOSING: Map = mapOf( - ')' to '(', - ']' to '[', - '}' to '{', - '>' to '<' + ')' to '(', ']' to '[', '}' to '{', '>' to '<' +) +val ERROR_SCORING: Map = mapOf( + ')' to 3, ']' to 57, '}' to 1197, '>' to 25137 ) -val ERROR_SCORING: Map = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) val AUTOCOMPLETE_SCORING: Map = mapOf( - '(' to 1, - '[' to 2, - '{' to 3, - '<' to 4 + '(' to 1, '[' to 2, '{' to 3, '<' to 4 ) -fun firstInvalid(input: String): Char? { +fun check(input: String): Pair> { val stack = mutableListOf() for (c in input) { if (CLOSING.contains(c)) { // found a closing one if (stack.size < 1 || stack.last() != CLOSING[c]) { - return c + return Pair(c, stack) } stack.removeLast() } else { stack.add(c) } } - return null + return Pair(null, stack) } fun part1(input: List): Int = input.sumOf { - firstInvalid(it)?.let { c -> - ERROR_SCORING[c] - } ?: 0 + check(it).let { (c, _) -> + ERROR_SCORING.getOrDefault(c, 0) + } } -fun getRemaining(input: String): List { - val stack = mutableListOf() - - for (c in input) { - if (CLOSING.contains(c)) { - stack.removeLast() - } else { - stack.add(c) +fun part2(input: List): 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 -> + scores[scores.size / 2] } - } - - return stack -} - -fun part2(input: List): 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] - } fun main() { val sample = readInput(10, "sample")