Created
January 31, 2013 16:32
-
-
Save zerosum/4684143 to your computer and use it in GitHub Desktop.
Project Euler: Problem 24
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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