I need to fill a int[2000][2000]
matrix with some logic.
My code for filling array:
// n: (1 to 2000)
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
uniMatrix[i][j] = (((calc(i * j * i * j)) & 1) == 0) ? 0 : 1;
}
}
Here: i * j * i * j
is my take on getting square of i*j
.
The calc()
is a method used to get a value. Then, I check if value returned by calc()
is even or odd. If it is even, I store 0
in matrix on (i, j)
, otherwise I store 1
in it.
My calc()
function is as below:
private static int calc(int n){
// value of n=calc(1 | 2 | 3) is known
if(n < 4) return n;
// if value is present in HashMap, return it (don't calculate again)
if(map.containsKey(n)) {
return map.get(n);
}
// calculate the answer
int answer = 1 * calc(n-1) + 2 * calc(n-2) + 3 * calc(n-3);
// store it in HashMap so that we don't have to recalculate it
map.put(n, answer);
return answer;
}
Now, If n
is 13, it creates a [13x13] matrix. But, for n=14
, it throws a StackOverflowError
at map.containsKey(n)
. I need to be able to make [2000x2000] matrices.
I know that the problem might be recursion. But, is there a way around this? Can I do something with BitSets(I don't have a clue on how to do it)?
I can use other datatype matrices: String[][]
or boolean[][]
too. I can't use a library outside Java SDK/JDK.
Edit: It is not a duplicate of "What is StackOverflowError?", I know what it is, I know why they occur. I need help in finding an alternative to my approach to prevent this error.