Skip to content

Instantly share code, notes, and snippets.

@zerosum
Created January 31, 2013 16:32
Show Gist options
  • Select an option

  • Save zerosum/4684143 to your computer and use it in GitHub Desktop.

Select an option

Save zerosum/4684143 to your computer and use it in GitHub Desktop.
Project Euler: Problem 24
package euler.zerosum
object Euler0024 {
def main(args: Array[String]) {
println(getArrangement(999999, (0 to 9).toList, Nil).mkString)
}
private def getArrangement(order: Int, objects: List[Int], arrangement: List[Int]): List[Int] = {
val unit = fact(objects.length - 1, 1)
val front = objects.zipWithIndex.takeWhile(unit*_._2 <= order)
val tail = objects.drop(front.length)
val next = front.last
val init = front.init.unzip._1
val left = order - unit * next._2
if (left == 0) {
arrangement ::: (next._1 :: init ::: tail)
} else {
getArrangement(left, init ::: tail, arrangement ::: next._1 :: Nil)
}
}
private def fact(n: Int, prod: Int): Int = if (n <= 1) prod else fact (n-1, n * prod)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment