This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Breaking for loops based on found results

No replies
Ståle Undheim
Joined: 2009-03-23,
User offline. Last seen 42 years 45 weeks ago.

When I am trying to learn a new language, I often go through stuff at
projecteuler.net. I haven't had too much time, so only at problem 4 in
scala:

"""
A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.
"""
The problem is easy enough, here is my isPalindrome method:
object Util {
def isPalindrome(txt: String, s:Int, e:Int):Boolean = {
if (s>e) true
else if (txt(s) == txt(e)) isPalindrome(txt,s+1,e-1)
else false
}
def isPalindrome(txt:String): Boolean = isPalindrome(txt,0,txt.length-1)
implicit def toStr(n:Int): String = n.toString
}

And here is my solution:
object Euler004 extends Application {
val palindromes = for {
a <- 100 to 999 reverse;
b <- a to 999 reverse;
if (isPalindrome(a*b))
} yield a*b
val results = palindromes.reduceRight((a,b)=> if (a>b) a else b)
println(results)
}

The problem here is that the 3rd result I find is actually the correct
one, but I end up finding all the palindromes when I just want to find
the largest. What I want here is that if a*b is a palindrome, I don't
need to examine smaller values of b, and if a*999 is smaller than the
biggest palindrome, I don't need to examine further. And if a*b is
smaller than the biggest palindrome, I don't need to examine further
values of b.

Are there ways to implement checks like this? Is there a functional
and short way to solve this, or do I need to rewrite to using while
loops?

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland