Skip to content

Instantly share code, notes, and snippets.

@almendar
Last active December 10, 2021 13:15
Show Gist options
  • Save almendar/9288ffe3c9b3c876a96d25622130889a to your computer and use it in GitHub Desktop.
Save almendar/9288ffe3c9b3c876a96d25622130889a to your computer and use it in GitHub Desktop.
import java.nio.file.{Files,Paths}
import scala.collection.mutable.ArrayDeque
import scala.collection.mutable
val mapping = Map(
']' -> '[',
')' -> '(',
'}' -> '{',
'>' -> '<'
)
val reverseMapping = mapping.map((k,v) => (v,k)).toMap
val scoring = Map(
')' -> 3,
']' -> 57,
'}' -> 1197,
'>' -> 25137,
)
def readLines(input: String) = Files.readString(Paths.get(input)).split("\n")
def countErrorScore(line:String) : (ArrayDeque[Char], Int) =
val deque = ArrayDeque.empty[Char]
for c <- line do
c match
case '[' | '(' | '{' | '<' => deque.prepend(c)
case ']' | ')' | '}' | '>' =>
if deque.isEmpty then
return (deque, scoring(c))
if mapping(c) != deque.removeHead() then
return (deque, scoring(c))
(deque,0)
def buildCompletion(chars: ArrayDeque[Char]): String =
val sb = mutable.StringBuilder(chars.length)
while(chars.nonEmpty)
sb += reverseMapping(chars.removeHead())
sb.result()
def task1(input: String) =
val lines = readLines(input)
val scores = for line <- lines
yield countErrorScore(line)._2
val sum = scores.sum
println(s"Day10 Task1 $input: ${sum}")
def scoreCompletion(completion: String): Int =
val scores = completion.map ( _ match
case ')' => 1
case ']' => 2
case '}' => 3
case '>' => 4
)
scores.foldLeft(0)((acc, el) => acc * 5 + el)
def task2(input: String) =
val toComplete = for
line <- readLines(input)
(deque, score) = countErrorScore(line) if score == 0
yield deque
val scores = for it <- toComplete yield
scoreCompletion(buildCompletion(it))
val finalScore = scores.sorted.apply(scores.length / 2)
println(s"Day10 Task2 $input: ${finalScore}")
@main def Day10() =
task1("example.txt")
task2("example.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment