I'm still playing with project Euler, and I'm going to love Scala more and more.
Yesterday, I solved the #42 problem, on which we need to parse a text file, and make some simple transformations and filtering on the results (it's why I choose this title, because it's generally the kind of things you expect to do in a scripting language, and well, I'm really
impressive, and I read this morning the post "Scala as a scripting language?", and I say "ho, it's exactly what I felt when I did pb#42 yesterday, let's blog on it, it's fashion :)
So, this problem is a simple Project Euler one (at least, there is no math on it), but just stop and think to what may look the Java's solution. Yes, you will have to deal with Files, input stream, and the like, filtering data, sorting things, and even if it's quite simple, it's always a little too heavy compared to what it may be.
So, there is the full solution in Scala, in a mixed imperative and functional style, as produced in the first sketch version (OK, I'm lying, in the first sketch, I didn't include comments and variables names looked more to 'lsv' and the like, these transformations are blog add-ons).
I'm sure there is a lot of optimizations available, but the important think is that Scala let you program as you think, whitout to much noise and boilerplate...
So let's go for the code:
package ex26_50
import scala.io.Source
object Problem42 extends Application {
def parseWords(file:String): List[String] = {
for {
line <- Source.fromFile(file).getLines.toList
s <- line.split(",")
if(!s.isEmpty)
} yield s.replaceAll("\"","")
}
def wordValue(s:String) : Int = {
var sum = 0
for(c <- s) {
val cval = c.toInt
if(cval >= 64 && cval <= 90) {
sum = sum + cval - 64
} else {
error("Unauthorized char: " + c.toString)
}
}
sum
}
val list_wordValues =
parseWords("src/words.txt").map(wordValue(_)).sort(_ > _)
println("Max value in %s words: %s (min: %s)".format(
list_wordValues.size,
list_wordValues.head,
list_wordValues.reverse.head))
val set_triangles = {
var set = Set[Int]()
var n = 1
var i = 1
while (n < max ) {
n = (i * (i+1))/2
i = i + 1
set = set.+(n)
}
set
}
val nb = list_wordValues.filter( (i:Int) =>
set_triangles.contains(i)).size
println("Found %s triangles words !".format(nb))
}
I love scala :)
PS: It's the full working solution, appart from the leading "_", sorry for the formatting, it seems that blogger is not the most friendly for code formatting. If somebody has some hint on that subject, I will be glad to heard them (ok, perhaps I should have a look on the plugins)
EDIT: I found a way to highlight code thanks to
SHJS. Thanks to the author for this plugin that wasn't to hard to make it work with blogger, and which the only Javascript highlighter that supports Scala :)