Question

114 void fillDoubly(int square[20][20], int n){
115
116     int i, j, k=0, l=0, counter=0, test[400]={0}, diff=n/4-1;
117
118     for(i=0;i<n;i++) //first nested for loops for part 1)
119         for(j=0;j<n;j++){
120             counter++;
121             if( i=j || j=(n-1-i) ){
122                 {
123                     square[i][j] = counter;
124                     test[counter-1] = 1;
125                 }
126             }
127         }
128
129     for(i=n-1;i>=0;i--) // for part 2)
130         for(j=n-1;j>=0;j--){
131             if(square[i][j]==0){
132                 while(test[k]!=0){
133                     k++;
134                 }
135                 test[k]=1;
136                 square[i][j]=k+1;
137             }
138         }
139 }

So basically, I have to generate magic square's of order 4 i.e. the rows and columns are divisible by 4.

I was provided the algorithm which is

  1. to traverse the array and fill in the diagonal subsets
  2. to traverse the array backwards and fill in the rest

I've done the 4x4 array with the above code and this extends to 8x8,12x12 etc. but I'm stuck at part 1) which is to fill in the diagonal subsets(e.g. split 8x8 into 4x4 and take that diagonal instead)...I'm not sure how to do that, only managed to fill in the diagonal itself

if( i=j || j=(n-1-i) ){

tldr, The above is the condition I use to know if it's diagonal, any suggestions how I can change the condition to know if it's the diagonal subset not diagonal?

Thanks

Was it helpful?

Solution

From what I understand from the tutorial you linked you wish to split your matrix into 16 equal submatrices, and fill take the diagonals accross these submatrices. Hence for a 8x8 matrix you want to achive:

 |   0    |    1    |    2    |    3   |  _
 0001 0002 0000 0000 0000 0000 0007 0008  0
 0009 0010 0000 0000 0000 0000 0015 0016  _
 0000 0000 0019 0020 0021 0022 0000 0000  1
 0000 0000 0027 0028 0029 0030 0000 0000  _
 0000 0000 0035 0036 0037 0038 0000 0000  2
 0000 0000 0043 0044 0045 0046 0000 0000  _
 0049 0050 0000 0000 0000 0000 0055 0056  3
 0057 0058 0000 0000 0000 0000 0063 0064  _

Here the submatrices are 2x2, if the matrix were 12x12, it would be subdivided into 16 submatrixes of 3x3.

If you use these submatrices as indexes with which to find the diagonal (i.e. i==j) you can use the expression:

if( (i/w)==(j/w)  || (j/w)==(3-(i/w)))

Where w = n/4, which is the order of your square submatrix (for 8x8, this is 2). So i/w will state in which submatrix (0 to 3) the current matrix index i resides.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top