Created
November 16, 2013 12:02
-
-
Save goldeneggg/7499416 to your computer and use it in GitHub Desktop.
Project Euler by scala No.32
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 ssbt | |
| object Euler32 { | |
| def main(args: Array[String]) { | |
| val permutations = List("1", "2", "3", "4", "5", "6", "7", "8", "9").permutations | |
| val pandigitalProducts = permutations.map(getPandigitalProductList(1, _)).toList.filter(_.size > 0) | |
| println("Answer %s".format(pandigitalProducts.flatten.distinct.sum)) | |
| } | |
| private def getPandigitalProductList(takeIndex: Int, permutaion: List[String], products: List[Int] = List[Int]()): List[Int] = { | |
| if (takeIndex > permutaion.size / 2) { | |
| products | |
| } else { | |
| val pd = getPandigitalProduct(permutaion.take(takeIndex).mkString, 1, permutaion.drop(takeIndex)) | |
| getPandigitalProductList(takeIndex + 1, permutaion, pd ::: products) | |
| } | |
| } | |
| private def getPandigitalProduct(firstMultiply: String, takeIndex: Int, list: List[String], products: List[Int] = List[Int]()): List[Int] = { | |
| if (list.size - firstMultiply.length < takeIndex) { | |
| products | |
| } else { | |
| val secondMultiply = list.take(takeIndex).mkString | |
| val product = list.drop(takeIndex).mkString | |
| val pd = if (firstMultiply.toInt * secondMultiply.toInt == product.toInt) product.toInt +: products else products | |
| getPandigitalProduct(firstMultiply, takeIndex + 1, list, pd) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment