count
takes Stream[Int]
and desiredNum
arguments. It adds the head of the stream (in a, I believe, lazy fashion) until the running sum >=
the desiredNum
.
Example: count(Stream.continually(1), 2)
should get output of 2 since 1 + 1 = 2
.
Here's my code:
def count(as: Stream[Int], desiredNum: Int): Option[Int] = {
def go(bs: Stream[Int], currentNum: Int, count: Int): Option[Int] =
bs match {
case x #:: xs if(currentNum >= desiredNum) => Some(count)
case x #:: xs => go(xs, currentNum + x, count + 1)
case Stream() => None
}
go(as, 0, 0)
}
Tests:
scala> count(Stream(1), 1)
res0: Option[Int] = Some(1)
scala> count(Stream.continually(1), 100)
res0: Option[Int] = Some(100)
EDIT Note that I changed my question after seeing that I was not checking the right value in my first case
statement. Initially I was using x
(head of Stream) rather than currentNum
. This led to an infinite loop.
But, is there a particular limit on desiredNum
with respect to CPU and RAM? Is this function correctly using Stream
's? (Perhaps there's a poor usage of RAM in count
?)