Skip to content

Instantly share code, notes, and snippets.

@goldeneggg
Created November 16, 2013 12:02
Show Gist options
  • Select an option

  • Save goldeneggg/7499416 to your computer and use it in GitHub Desktop.

Select an option

Save goldeneggg/7499416 to your computer and use it in GitHub Desktop.
Project Euler by scala No.32
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