There's something wrong in my Magic Square Algorithm

528 views Asked by At

Hi I created a Magic Square program in java It works fine if you input a number 3 but if i input 5 and so on there's a problem occurring.. The pattern becomes wrong.

Please help me to find out what's wrong in my code:

Here's my code:

    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int num = input.nextInt();

    // Number must be ODD and not less than or equals to one to continue
    while ((num % 2 == 0) || (num <= 1)) {
        System.out.println("Enter a valid number: ");
        num = input.nextInt();
    }

    int[][] magic = new int[num][num];

    int row = 0;
    int col = num / 2;
    magic[row][col] = 1;

    for (int i = 2; i <= num * num; i++) {
        if (magic[(row + 5) % num][(col + 2) % num] == 0) {
            row = (row + 5) % num;
            col = (col + 2) % num;
        } else {
            row = (row + 1 + num) % num;
        }
        magic[row][col] = i;
    }

    for (int x = 0; x < num; x++) {
        for (int j = 0; j < num; j++) {
            System.out.print(magic[x][j] + "\t");
        }
        System.out.println();
    }

}

It's correct when i Input 3, here's the output:

enter image description here

But when i type a number like 5: It becomes:

enter image description here

UPDATED!

1

There are 1 answers

2
OldCurmudgeon On

You seem to be trying to implement the Method for constructing a magic square of odd order.

The method prescribes starting in the central column of the first row with the number 1.

You seem to have that right.

After that, the fundamental movement for filling the squares is diagonally up and right, one step at a time.

I would code this as:

int newRow = row - 1;
int newCol = col + 1;

When an "up and to the right" move would leave the square, it is wrapped around to the last row or first column, respectively.

This is clearly:

if ( newRow < 0 ) {
  newRow = num - 1;
}
if ( newCol > num - 1 ) {
  newCol = 0;
}

If a filled square is encountered, one moves vertically down one square instead, then continues as before.

if (magic[newRow][newCol] != 0) {
  newRow = row + 1;
  newCol = col;
}

I know this doesn't actually solve your problem but I hope it gets you somewhere towards your goal. See how I take the words of the algorithm and match them as accurately as possible with code.