Scala Find the smallest cube for which exactly five permutations of its digits are cubes

I ran into this amazing problem and tried to solve it in scala to learn the language. A brief explanation of the problem in the title and here is a longer explanation http://www.mathblog.dk/project-euler-62-cube-five-permutations/ .

I solved it in Javascript and tried to pass the logic to scala, but that didn’t quite work. It works to search for 3 permutations, but not 4, 5, and probably up.

Here is the code:

import collection.mutable.Map
import collection.mutable.{Map => MMap}

val mutMap3 = MMap.empty[String, MMap[String, Int]]
def pow(n:Int) : Int =  { 
  val cubed = (n * n * n).toString
  val digits = 0 to 9
  var str = ""
  for (a <- digits) {
    val b = cubed.count(_.toString==a.toString)
    str += b
  }
  if (mutMap3 contains str) {
    mutMap3(str)("len") += 1
    if(mutMap3(str)("len") == 5) {
      return mutMap3(str)("first")
    }
  } else {
    mutMap3(str) = MMap("len" -> 1, "first" -> n)
  }
  return pow(n+1)
}

, , (.. 4233 3234), , , . 4233 "0" 0 , "1" 0 , "2" 2 , "4" 1 , "5" 0 ... .. 9, "0012100000", "0123456789" ( 4233, 3234, "2", "3" "4" "0012100000" ). , , , , , + 1 , 5 , , .

, , . !

+4
1

, :

scala> val cubes=(0 to 5030).map(c=>c.toLong*c*c).toSet

cubes: scala.collection.immutable.Set[Long] = Set(2628072, ...

scala> cubes.par.filter(_.toString.permutations.map(_.toLong).filter(cubes.contains(_)).length==5)

res6: scala.collection.parallel.immutable.ParSet[Long] = ParSet(38614472000, 10648000000, 10403062487, 91125000000, 65939264000, 54439939000, 95443993000, 122763473000, 116500279104, 114791256000, 40920960536, 103823000000)
+1

Source: https://habr.com/ru/post/1526489/


All Articles