I am a Scala newbie, just starting to learn the language.
I solved Problem 8 from Project Euler page.
The code looks like this (I removed all the code to do with reading of an input file):
def max(n1: Int, n2: Int): Int = Math.max(n1, n2) def max_product(digits: List[Int], num: Int): Int = { def max_core(lst: List[Int], curr_max: Int): Int = lst match { case a if lst.length >= num => max_core(a.tail, max(lst.slice(0, num).reduceLeft(_*_), curr_max)) case _ => curr_max } max_core(digits, 0) } println(max_product(1::2::3::4::2::3::Nil, 2))
It works fine, the result is correct. However, I am not completely satisfied with this solution. I don't like the max_core
sub-function and have the feeling it can be improved. My understanding of FP is, you should iterate over a list, slicing seems to not be the way here.
The question is: how?
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, instead of slice
is deprecated, thereforelst.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
This is the way I did it. Nothing fancy. In your code, you were taking the length of the list in every iteration which is rather wasteful. I just append the some number of 1s (same as the number of consecutive digits) to the end of the list so I don't need to check the length of the list in order to terminate the loop.
val s = ... // string of digits
val ds = s.map(_.asDigit).toList
def findMaxProduct(ds: List[Int], n: Int, max: Int): Int = ds match {
case Nil => max
case _ :: rest => findMaxProduct(rest, n, Math.max(max, ds.take(n).reduceLeft(_ * _)))
}
val n = 5 // number of consecutive digits
println(findMaxProduct(ds ::: List.make(n, 1), n, -1))
val str = ... // string of digits
val nums = str.map{ _.asDigit }
(0 to nums.size-5).map{ i => nums.slice(i,i+5).product }.max
and another one, more efficient:
(0 to nums.size-5).foldLeft(-1){case(r,i) => r max nums.slice(i,i+5).product}
BTW: works with scala2.8
val bigNumber = """73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450""".replaceAll("\\s+","")
def getMax(m: Int, l:List[Seq[Int]]): Int =
if (l.head.isEmpty) m else
getMax(m max l.foldLeft(1) ((acc, l) => acc * l.head), l map (_ tail))
def numDigits(bigNum: String, count: Int) =
(1 until count).foldLeft(List(bigNumber map (_ asDigit))) ((l, _) => l.head.tail :: l)
def solve(bigNum: String, count: Int) = getMax(0, numDigits(bigNum, count))
solve(bigNumber, 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With