3x3 magic square algorithm problem

3x3 magic square is an NxN matrix in which every row, column, and diagonal add up to the same number.

the algorithm:

Start with the middle entry of the top row. Place a 1 there. Now we'll move consecutively through the other squares and place the numbers 2, 3, 4, etc. It's easy: after placing a number, just remember to always move:

1. diagonally up and to the left when you can,
2. go down if the box is already occupied

The only thing you must remember is to imagine the matrix has "wrap-around", i.e., if you move off one edge of the magic square, you re-enter on the other side.

My only problem is that in my algorithm is the go down if its occupied, its actually going down but it must be in the previous box, not on the next box,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 #include <iostream>

using namespace std;

int main ()
{
int magicsq[3][3];
int i,j,x;

int row=0;		//start positon of row
int col=3/2;	// and colum
 
	for( i=0;i<3;i++)
	{
		for(j=0;j<3;j++)
		{
			magicsq[i][j] = 0;		//initialize to 0 your matrix
		}	
	}
 
 magicsq[row][col] = 1;		//position to star the counting
 
 for(x=2;x<=3*3;x++)
 {
 	row--;
 	col--;
 
 	if(row<0){
 		row=row+3;
	 }

	if(col<0){
		col=col+3;
	}
	
	if (magicsq[row][col]>0){
		row++;					//i think this is the part of the problem?
	}

 	magicsq[row][col] = x;
 }
 
 for( i = 0; i<3;i++){
 	for(j = 0; j<3;j++)
 	{
 		cout<<magicsq[i][j] <<" ";
	 }
	 cout<<endl;
 }
}
Every time that you adjust a row or column then you must check for wraparound. You don't currently do so after line 37. Here, you need to check that row is not >= 3.

Ultimately, you will also have to remove 3 as a "magic number" as well.
so even if i add if(row>=3){row-=3;} before line 36 it still wont produce the magic number. i guess i have to think another algorithm. thanks
Try
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

int main ()
{
   int magicsq[3][3];
   int i, j, x;

   int row = 0;              // start position of row
   int col = 3 / 2;          // and column
 
   for ( i = 0; i < 3 ; i++ )
   {
      for ( j = 0 ; j < 3; j++ ) magicsq[i][j] = 0;              //initialize to 0 your matrix
   }
 
   magicsq[row][col] = 1;         //position to start the counting
 
   for ( x = 2; x <= 3 * 3; x++ )
   {
      int r = row - 1, c = col - 1;    // test positions
      if (r < 0) r += 3;
      if (c < 0) c += 3;
      if ( magicsq[r][c]>0)
      {
         row++;
         if ( row >= 3 ) row -= 3;
      }
      else
      {
         row = r;
         col = c;
      }
      magicsq[row][col] = x;
   }
 
   for ( i = 0; i < 3; i++ )
   {
      for ( j = 0; j < 3; j++ ) cout << magicsq[i][j] << " ";
      cout<<endl;
   }
}
Last edited on
thank you.
Topic archived. No new replies allowed.