Question

I'm trying to solve this problem http://projecteuler.net/problem=62 and I am getting hung up on this error:

euler.scala:10: error: type mismatch;
found   : Array[Any]
 required: Array[Int]
Note: Any >: Int, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ >: Int`. (SLS 3.2.10)
    master(perm) = if (master.contains(perm)) master(perm) :+ cube else Array(cube)
                                                           ^
one error found

The problem may be because of the BigInt trying to be stored in an Array, but aparently there is no such thing as an array with Array[BigInt]

Below is my code:

import scala.util.control.Breaks._

var m = new scala.collection.mutable.LinkedHashMap[String,Array[Int]]
var master = m.withDefaultValue(Array.empty[Int])
val range = 345 to 9999

    range.foreach { n =>
    val cube = BigInt(n) * n * n
    val perm = cube.toString.map(_.asDigit).mkString("")
    master(perm) = if (master.contains(perm)) master(perm) :+ cube else Array(cube)
}

master.values.foreach { value =>
    if (value.length >= 5) {
        println (Math.cbrt(value(0)))
        break
    }
}
Was it helpful?

Solution

cube is of type BigInt. So Array(cube) is of type Array[BigInt]

The type of master(perm) is Array[Int], and you are trying to do

Array[Int] :+ BigInt => Array[Int], which does not work.

Suggestion: Make all your arrays of type BigInt.

So:

var m = new scala.collection.mutable.LinkedHashMap[String,Array[BigInt]]
var master = m.withDefaultValue(Array.empty[BigInt])

Also consider using a List, instead of an array. That :+ operator will allocate a new array each time. If you use Lists, they are smarter, will perform these immutable operations more efficiently.

OTHER TIPS

There is Array[BigInt], but that is different than Array[Int]. In fact, the common supertype of BigInt and Int is Any, which is why that's appearing in your error messages: when you append cube, which is a BigInt to master(perm), which is and Array[Int], you'll get an Array which has both Int and BigInt, and the only type that supports both is Array[Any].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top