ScalaでProject Euler(61)

Problem 34

Problem 30とほとんど同じです。

def pow(n :Int, e :Int) = (1 to e).foldLeft(1L)((x, y) => x * n)
def factorial(n :Int) = (1 to n).foldLeft(1)(_ * _)

def digits(n :Long) :List[Int] =
    if(n == 0) Nil else (n % 10).toInt :: digits(n / 10)

def repeated_combination[T](a :List[T], n :Int) :Iterator[List[T]] =
    (a, n) match {
        case (_, 0) => Iterator(Nil)
        case (Nil, _) => Iterator()
        case _ => repeated_combination(a, n - 1).map(a.head :: _) ++
                                        repeated_combination(a.tail, n)
}

def calc_upper() =
    Iterator.from(1).filter(e => factorial(9) * e < pow(10, e)).next

val facts = Array.range(0, 10).map(factorial)
val e = calc_upper

def is_valid(a :List[Int]) =
    a == digits(a.map(facts(_)).sum).sort(_ < _)

val it = for(n <- Iterator.range(2, e + 1);
             a <- repeated_combination(List.range(0, 10), n)
             if is_valid(a)) yield a
println (it.map(_.map(facts(_)).sum).sum)