8000 Improve 2018 day 8 by removing stateful Seq.fill · sim642/adventofcode@7b70dd9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7b70dd9

Browse files
committed
Improve 2018 day 8 by removing stateful Seq.fill
1 parent 7bd0760 commit 7b70dd9

File tree

1 file changed

+11
-7
lines changed
  • src/main/scala/eu/sim642/adventofcode2018

1 file changed

+11
-7
lines changed

src/main/scala/eu/sim642/adventofcode2018/Day8.scala

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,20 @@ object Day8 {
1818
}
1919
}
2020

21+
def replicateParser[A, B](n: Int, a: A)(f: A => (B, A)): (Seq[B], A) = {
22+
if (n <= 0)
23+
(Seq.empty, a)
24+
else {
25+
val (b, a2) = f(a)
26+
val (bs, a3) = replicateParser(n - 1, a2)(f)
27+
(b +: bs, a3)
28+
}
29+
}
30+
2131
def parseTree(seq: List[Int]): Tree = {
2232
def helper(seq: List[Int]): (Tree, List[Int]) = seq match {
2333
case childrenCount :: metadataCount :: tl =>
24-
var seq = tl
25-
// TODO: fix this stateful fill
26-
val children: Seq[Tree] = Seq.fill(childrenCount)({
27-
val (child, seq2) = helper(seq)
28-
seq = seq2
29-
child
30-
})
34+
val (children, seq) = replicateParser(childrenCount, tl)(helper)
3135
val (metadata, seq2) = seq.splitAt(metadataCount)
3236
(Tree(children, metadata), seq2)
3337
}

0 commit comments

Comments
 (0)
0