Created
December 10, 2021 16:12
-
-
Save ende76/485e516dad4d3edc22a8f471373a1eb5 to your computer and use it in GitHub Desktop.
Solution for part 2 of https://adventofcode.com/2021/day/10
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.* | |
private fun readChar(): Char = readString()[0] | |
private fun readChars(): CharArray = readString().toCharArray() | |
private fun readInt(): Int = readLine()!!.toInt() | |
private fun readInts(): List<Int> = readLine()!!.trim().split(" ").map(String::toInt) | |
private fun readLong(): Long = readLine()!!.toLong() | |
private fun readLongs(): List<Long> = readLine()!!.trim().split(" ").map(String::toLong) | |
private fun readString(): String = readLine()!!.trim() | |
private fun readStrings(): List<String> = readLine()!!.trim().split(" ") | |
fun main() { | |
val opening = setOf('(', '[', '{', '<') | |
val matching = mapOf(Pair('(', ')'), Pair('[', ']'), Pair('{', '}'), Pair('<', '>')) | |
val score = mapOf(Pair('(', 1L), Pair('[', 2), Pair('{', 3), Pair('<', 4)) | |
var nextLine = readString() | |
val scores = mutableListOf<Long>() | |
nextLine@while (nextLine.isNotEmpty()) { | |
var totalScore = 0L | |
val stack = ArrayDeque<Char>() | |
for (c in nextLine) { | |
if (c in opening) stack.offerLast(c) | |
else if (stack.isNotEmpty() && matching[stack.peekLast()] == c) stack.pollLast() | |
else { | |
nextLine = readString() | |
continue@nextLine | |
} | |
} | |
while (stack.isNotEmpty()) { | |
totalScore *= 5 | |
totalScore += score[stack.pollLast()]!! | |
} | |
scores.add(totalScore) | |
nextLine = readString() | |
} | |
scores.sort() | |
println(scores[scores.size / 2]) | |
} | |
/* | |
[({(<(())[]>[[{[]{<()<>> | |
[(()[<>])]({[<{<<[]>>( | |
(((({<>}<{<{<>}{[]{[]{} | |
{<[[]]>}<{[{[{[]{()[[[] | |
<{([{{}}[<[[[<>{}]]]>[]] | |
[({(<(())[]>[[{[]{<()<>> | |
[(()[<>])]({[<{<<[]>>( | |
{([(<{}[<>[]}>{[]{[(<()> | |
(((({<>}<{<{<>}{[]{[]{} | |
[[<[([]))<([[{}[[()]]] | |
[{[{({}]{}}([{[{{{}}([] | |
{<[[]]>}<{[{[{[]{()[[[] | |
[<(<(<(<{}))><([]([]() | |
<{([([[(<>()){}]>(<<{{ | |
<{([{{}}[<[[[<>{}]]]>[]] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment