samskivert: Euler 051

18 August 2008

Problem 051:

object Euler51 extends EulerApp {
  def cprimes (n :String)(d :Char) = {
    val variants = 0123456789.toList.map(nd => n.replace(d, nd))
    variants.filter(!_.startsWith("0)).map(Integer.parseInt).filter(isprime).length
  }
  def count (prime :String) = {
    prime.toList.removeDuplicates.map(cprimes(prime)).reduceRight(Math.max)
  }
  println(genprimes(150000).filter(0.!=).find(p => count(p.toString) > 7).get)
}

A robust set of functional libraries really makes our lives easier here. Our function for obtaining the count of primes that can be generated by substituting all digits for one particular digit in the original prime takes our number as a string, turns that into a list of digits, removes duplicates, maps a (curried) function onto each of those individual digits and then folds the resulting list with max to find the largest value. You could throw a rock and hit a hundred Java programs that use ten lines to do any one of those operations and we do all four in one concise and expressive line.

©1999–2015 Michael Bayne