Saturday, October 24, 2009

Simple problem solving using Scala

If you like solving mathematical problems using Scala, i would suggest that you sign up at Project Euler (Thanks to my good friend Chi Hung for getting me hooked!) and use your favourite programming language or languages to solve it (There is more than 1 way to accomplish a goal)

So here's my take on it using Scala and just to provide an example, i'm using problem 4
scala> var largest = 1
largest: Int = 1

scala> for(i <- 1 until 1000) for( j <- i until 1000) {
|  val v = i*j                                            
|  if ((v.toString.reverse.mkString) == (v.toString)) {     
|   if (v > largest) largest = v               
|  }
| }

scala> largest
res5: Int = 906609

This is not efficient since i'm looking for the largest palindrome made from 2 3-digit numbers so i should reverse this and possibly limit the data ranges to perhaps half. Anyway, i'd like to show you how this simple function can be factored into a style more Scala-like.

scala> var largest = 1
largest:Int = 1

scala> def isPalindrome(s:Any):(Boolean,Any) = {
|  if (s.toString.reverse.mkString == s.toString) (true,s)
|  else (false,s)
| }
isPalindrome: (Any)(Boolean, Any)
scala> (1 to 100).map(i => (1 to 100).map(j => if ( isPalindrome(i*j)._1 && (i*j) > largest) largest = (i*j)))
scala> largest
res12: Int = 9009
scala> (1 to 1000).map(i => (1 to 1000).map(j => if ( isPalindrome(i*j)._1 && (i
*j) > largest) largest = (i*j)))
res13: RandomAccessSeq.Projection[RandomAccessSeq.Projection[Unit]] = RangeM(Ran
geM((), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (),
(), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (),
(), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (),
(), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (),...
scala> largest
res14: Int = 906609

Ignore the part on the variable res13 and this version ran pretty fast for me too and i like this version much better than the former. It can be faster but i'd like to show you how to solve problems for now.

Feedback is appreciated!


0 comments: