-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8.scala
48 lines (38 loc) · 1.37 KB
/
8.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
41
42
43
44
45
46
47
48
import scala.collection.immutable.Queue
val seq = io.Source.stdin.mkString.trim.split(' ').map(_.toInt)
case class Node(metadata: Seq[Int], children: Node*)
def buildTree(seq: Seq[Int]): Node = {
def recurse(seq: Queue[Int]): (Node, Queue[Int]) = {
val (numChildren, seq2) = seq.dequeue
val (metadataCount, seqChildren) = seq2.dequeue
if (numChildren == 0) {
(Node(seqChildren.take(metadataCount)), seqChildren.drop(metadataCount))
} else {
val (children: List[Node], tailSeq: Queue[Int]) = (1 to numChildren).foldLeft((List.empty[Node], seqChildren)) {
case ((list, subSeq), _) =>
val (child, restSeq) = recurse(subSeq)
(list :+ child, restSeq)
}
(Node(tailSeq.take(metadataCount), children: _*), tailSeq.drop(metadataCount))
}
}
recurse(Queue(seq: _*))._1
}
def printTree(node: Node): Unit = {
def print(node: Node, depth: Int): Unit = {
println((" " * depth) + node.metadata.mkString(","))
node.children.foreach(print(_, depth + 1))
}
print(node, 0)
}
def checksum(node: Node): Int = node.metadata.sum + node.children.map(checksum).sum
def checksum2(node: Node): Int = {
if (node.children.isEmpty) {
node.metadata.sum
} else {
node.metadata.map(i => node.children.lift(i - 1).map(checksum2).getOrElse(0)).sum
}
}
val tree = buildTree(seq)
println(checksum(tree))
println(checksum2(tree))