Skip to content

Instantly share code, notes, and snippets.

@ende76
Created December 10, 2021 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ende76/485e516dad4d3edc22a8f471373a1eb5 to your computer and use it in GitHub Desktop.
Save ende76/485e516dad4d3edc22a8f471373a1eb5 to your computer and use it in GitHub Desktop.
Solution for part 2 of https://adventofcode.com/2021/day/10
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