3

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
    }
}
David Melin
  • 302
  • 2
  • 11
  • 1
    BigInt and Int are similar in the same sense in which Int is similar to say Thread. You can't just concat arrays of those two completely different types that has only Any as a common ancestor, perhaps you would be better to switch to BigInt completely? – om-nom-nom Oct 17 '13 at 21:13

2 Answers2

3

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.

triggerNZ
  • 4,221
  • 3
  • 28
  • 34
1

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].

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681