I am trying to solve the following problem:
Given a number n, generate a matrix of size 2^n * 2^n such that respects the following rule:
n = 1
[ 1 2 ]
[ 3 4 ]
n = 2
[ 1 2 5 6 ]
[ 3 4 7 8 ]
[ 9 10 13 14 ]
[ 11 12 15 16 ]
Here is my algorithm:
static void generare(int i , int j , int x , int y){
if(x - i == 1 && y - j == 1)
{
mat[i][j] = counter++;
mat[i][j+1] = counter++;
mat[i+1][j] = counter++;
mat[i+1][j+1] = counter++;
}
else{
generare(i,j,x/2,y/2);
generare(i,y/2+1,x/2,y);
generare(x/2+1,j,x,y/2);
generare(x/2+1,y/2+1,x,y);
}
}
It works for n = 1,2 but when I try any number > 2, it crashes. How can i fix my recursive function?