Skip to content

Commit 84adb0f

Browse files
author
Kalle Wuoti
committed
Use streams on day 1 exercise
1 parent a478a82 commit 84adb0f

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

day1/prog.scala

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,17 @@
11
import scala.io.Source
22

3-
val pars = Source.fromFile("input.txt").toList
3+
val pars = Source.fromFile("input.txt").toStream
44

55
def upOrDown(c: Char) = if (c == '(') 1 else -1
66

77
val finalFloor = pars.foldLeft(0)((floor, p) => floor + upOrDown(p))
88

9-
def foo(floor: Int, seq: Int, pars: List[Char]): Int = {
10-
if (floor == -1) seq
11-
else pars match {
12-
case h :: t => foo(floor + upOrDown(h), seq + 1, t)
13-
case Nil => sys.error("Never reached basement")
14-
}
15-
}
16-
17-
val firstTimeInBasement = foo(0, 0, pars)
9+
val firstTimeInBasement = pars
10+
.map(upOrDown)
11+
.scanLeft(0){ case (floor, d) => floor + d }
12+
.zipWithIndex
13+
.filter(_._1 == -1)
14+
.head._2
1815

1916
println(s"The instructions take santa to floor $finalFloor")
2017
println(s"The first time santa enters the basement is at instruction number $firstTimeInBasement")

0 commit comments

Comments
 (0)