-
-
Save waynejo/c4bd3f819a75f3da2470ee92a43c5c77 to your computer and use it in GitHub Desktop.
This file contains 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.io.FileInputStream | |
import scala.annotation.tailrec | |
import scala.io.StdIn | |
def parse(text: String): Either[Char, Vector[Char]] = | |
@tailrec | |
def _parse(acc: Vector[Char], index: Int): Either[Char, Vector[Char]] = | |
if text.length <= index then | |
Right(acc) | |
else | |
text(index) match | |
case c @ ('(' | '[' | '{' | '<') => | |
_parse(acc :+ c, index + 1) | |
case ')' if acc.lastOption.contains('(') => | |
_parse(acc.init, index + 1) | |
case ')' => | |
Left(')') | |
case ']' if acc.lastOption.contains('[') => | |
_parse(acc.init, index + 1) | |
case ']' => | |
Left(']') | |
case '}' if acc.lastOption.contains('{') => | |
_parse(acc.init, index + 1) | |
case '}' => | |
Left('}') | |
case '>' if acc.lastOption.contains('<') => | |
_parse(acc.init, index + 1) | |
case '>' => | |
Left('>') | |
_parse(Vector(), 0) | |
def solve10_1(inputs: Vector[String]): Int = | |
inputs.foldLeft(0) { (acc, v) => | |
val score = parse(v) match | |
case Left(')') => 3 | |
case Left(']') => 57 | |
case Left('}') => 1197 | |
case Left('>') => 25137 | |
case _ => 0 | |
score + acc | |
} | |
def scoreOfAutocomplete(text: Vector[Char]): BigInt = | |
text.reverse.foldLeft(BigInt(0)) { (acc, v) => | |
val score = v match { | |
case '(' => 1 | |
case '[' => 2 | |
case '{' => 3 | |
case '<' => 4 | |
} | |
acc * 5 + score | |
} | |
def solve10_2(inputs: Vector[String]): BigInt = | |
val scores = inputs.flatMap { v => | |
parse(v) match | |
case Right(text) => | |
Some(scoreOfAutocomplete(text)) | |
case _ => | |
None | |
} | |
scores.sorted.toVector(scores.length / 2) | |
@main def solve10(): Unit = | |
val in = new FileInputStream("example10-2.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()) | |
.takeWhile(line => null != line && line.trim.nonEmpty) | |
.toVector | |
println(solve10_1(inputs)) | |
println(solve10_2(inputs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment