First, I would not reinvent the wheel... the method max already is defined in RichInt
, so you can write a max b
, for a
and b
integers.
ALso, slice
is deprecated, therefore instead of lst.slice(0, num)
I would use lst.take(num)
. Deprecated methods will probably be gone when Scala 2.8 is launched.
EDIT: Indeed, as Daniel pointed out, slice(Int, Int)
is not deprecated. I was quite in a hurry when I initially wrote this, and I was thinking of slice(Int)
, which is equivalent to drop(Int)
. I still find lst.take(num)
to be clearer than lst.slice(0, num)
:).
(nitpick) Your last line does also not compile as you forgot to add Nil
to the end of your sequence of cons. 1::2::3::4
, would end up invoking ::
on an Int
, which does not have this method. That's why you need to add Nil
to the end (invoke ::
on Nil
).
Also, the algorithm you have used is not obvious at the first glance. The way I would write this is as follows:
val numbers = /*"--the string of numbers--"*/.map(_.asDigit).toList
def sliding[A](xs: List[A], w: Int): List[List[A]] = {
for(n <- List.range(0, xs.size - w))
yield xs drop n take w
}
def product(xs: List[Int]): Int = (1 /: xs) (_ * _)
sliding(numbers, 5).map(product).sort(_ > _).head
I feel that the last line explains quite well what the algorithm is supposed to do - take a sliding window of the list, calculate the product in that sliding window and then get the maximum of the calculated products (I have implemented the maximum function as sort(_ > _).head
out of laziness, I could have done something O(n) rather than O(n log(n)) if performance was critical... it still runs under a second though).
Note that the sliding function will be in the Scala 2.8 library (see Daniel's post, from where I was inspired in writing this definition of sliding).
EDIT: Oops... sorry about the /:
. I just like the conciseness of it and the fact that the initial element of the fold comes before the list. You could equivalently write product
as the following, to be more explicit:
def product(xs: List[Int]): Int = xs.foldLeft(1)(_ * _)
-- Flaviu Cipcigan