I'm training with Java 8 streams, trying to implement the same logic as in this Scala code I also wrote :
def solution = {
var s = "input"
var n = Math.sqrt(s.length / 3).toInt
val arr = s.split("\\s+").map(_.toInt)
def prod(index : Int, count : Int = 4)(inc : Int) : Int =
if (count > 0) arr(index)*prod(index + inc,count - 1)(inc) else 1
def prodInRange(rows : Seq[Int], cols : Seq[Int])(inc : Int) =
for (i <- rows ; j <- cols) yield prod(n*i + j)(inc)
val seq = prodInRange(0 to 19,0 to 16)( 1 ) ++ prodInRange(0 to 16,0 to 19)( n ) ++
prodInRange(0 to 16,0 to 16)(n + 1) ++ prodInRange(3 to 19,0 to 16)(1 - n)
seq.max
}
I implemented prod
in Java, nothing special about that, and the method solution is also quite the same. However, I'm having a hard time with prodInRange
. I change it to maxProdInRange
, which is supposed to compute not only all the products but also their maximum. Here is the code :
public static int maxProdInRange(IntStream rows, IntStream cols, int inc, List<Integer> input) {
int n = (int) Math.sqrt(input.size());
return rows.flatMap(i -> cols.map(j -> prod(i*n + j,inc,input))).max().getAsInt();
}
Nevertheless, I'm having an exception (see title) when calling maxProdInRange. According to the tests I ran to try to debug it, it occurrences only when I call max(). First, I would like to know why I get this error (I think it comes from a misconception about Java streams) and also a way to fix it.
Note that in all the calls to maxProdInRange
have the form maxProdInRange(IntStream.range(a,b),IntStream.range(a,b),input)
so rows and cols are neither operated nore closed when passed as parameters.