samskivert: Euler 022

18 January 2008

Problem 022:

import scala.io.Source;
object Euler22 extends Application {
  def trim (name :String) = name.slice(1, name.length-1);
  val names = Source.fromFile("names.txt").getLine(0).split(',').map(trim).toList.sort(_<_);
  def score (name :String) = name.foldLeft(0)((s, l) => (s + (l - 'A' + 1)))
  println(List.range(0, names.length).map(i => ((i+1) * score(names(i)))).foldLeft(0)(_+_));
}

Another reasonably legible solution. I resisted the urge to do it all in a single expression.

I can see how language designers might succumb to the urge to expose a loop counter in their iteration functions because it would be nice to do:

println(names.map(name => ((_INDEX_+1) * score(name))).foldLeft(0)(_+_));

©1999–2015 Michael Bayne