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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With