-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolutiona.scala
40 lines (35 loc) · 1.27 KB
/
solutiona.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import scala.util.matching.Regex
trait Node
case class Op(op: (Long, Long) => Long, left: String, right: String) extends Node
case class Num(value: Long) extends Node
object Solution {
val addPattern: Regex = """^(\w+): (\w+) \+ (\w+)$""".r
val subPattern: Regex = """^(\w+): (\w+) - (\w+)$""".r
val mulPattern: Regex = """^(\w+): (\w+) \* (\w+)$""".r
val divPattern: Regex = """^(\w+): (\w+) / (\w+)$""".r
val numPattern: Regex = """^(\w+): (\d+)$""".r
def evaluate(nodes: Map[String, Node], current: String): Long =
nodes(current) match {
case Op(op, left, right) =>
op(evaluate(nodes, left), evaluate(nodes, right))
case Num(value) => value
}
def main(args: Array[String]): Unit = {
val nodes = io.Source.stdin.getLines().map { line =>
line match {
case addPattern(id, left, right) =>
(id, Op(_ + _, left, right))
case subPattern(id, left, right) =>
(id, Op(_ - _, left, right))
case mulPattern(id, left, right) =>
(id, Op(_ * _, left, right))
case divPattern(id, left, right) =>
(id, Op(_ / _, left, right))
case numPattern(id, value) =>
(id, Num(value.toLong))
}
}.toMap
val result = evaluate(nodes, "root")
println(result)
}
}