Reputation: 1
I'm trying to construct n-odd magic squares through the Siamese method
Here's my code
#include <iostream>
#include <cstring>
using namespace std;
int main(){
int N; cin >> N;
int magicsquares[N][N];
memset(magicsquares, 0, sizeof(magicsquares));
int i = 0, j = N/2;
int num = 1;
while (num <= N*N){
if (magicsquares[i][j] == 0){
magicsquares[i][j] = num++;
i = (i-1+N) % N;
j = (j+1) % N;
} else{
i = (i+2) % N;
j = (j-1+N) % N;
magicsquares[i][j] = num++;
}
}
for (int a = 0; a < N; a++){
for (int b = 0; b < N; b++)
cout << magicsquares[a][b] << " ";
cout << endl;
}
return 0;
}
When I typed in 3, I expected it to come out like this:
8 1 6
3 5 7
4 9 2
But it came out like this:
0 9 0
3 0 8
7 0 2
What's wrong with my code? I can't figure it out
Upvotes: 0
Views: 50
Reputation: 371
In the if
branch (unfilled square), you fill a square and then set up i
and j
to point to the next square to be filled. When you encounter a filled square (else
branch), you reverse the change in i
and j
and go down as per the algorithm, and fill it. But after that, you are not setting up i
and j
for the next move, like in the if
branch. Setting i
and j
should be there for both branches. This should work:
if (magicsquares[i][j] == 0){
magicsquares[i][j] = num++;
} else{
i = (i+2) % N;
j = (j-1+N) % N;
magicsquares[i][j] = num++;
}
i = (i-1+N) % N; /* Setting up i and j for next fill */
j = (j+1) % N; /* This should be done in both cases */
Upvotes: 2