I'm new to Scala and learn it by solving some Project Euler problems. Here is the solution to problem 42 from Project Euler.
The task is to read words from file, then sum ordinal numbers of each character (e.g. sky =19+11+25=55). One need to count all words for which this sum is a triangular number (satisfying \$\frac{n(n+1)}{2}\$ for some \$n\$).
import scala.io.Source
import java.nio.file.Files
import java.nio.file.Paths
def makeTriangleNumber(word:String): Int = {
word.map(ordinals(_)).reduceLeft(_ + _)
}
val inputFile = Paths.get(args(0));
assert(Files.exists(inputFile))
val ordinals = ((('A' to 'Z').toList) zip Stream.from(1)).toMap
assume(ordinals('Z') == 26)
var triangleNumbers = scala.collection.SortedMap(1 -> 1)
val words = Source.fromFile(inputFile.toUri()).getLines.mkString.replace("\"", "").split(",").toList
var counter = 0
assert(makeTriangleNumber("SKY") == 55)
for (w <- words) {
var candidate = makeTriangleNumber(w)
if (!triangleNumbers.contains(candidate) && candidate > triangleNumbers.max._1) {
var tmp = Stream.from(triangleNumbers.max._2 + 1)
.map((x) => (x * (x + 1) / 2, x))
.takeWhile(_._1 <= candidate)
triangleNumbers = triangleNumbers ++ tmp.toMap
}
if (triangleNumbers.contains(candidate)) {
counter += 1
}
}
println("The answer is: " + counter)