How could I reverse the output of my Magic Square

370 views Asked by At

I wrote a magic square program and it's run good.

But I need to reverse the output of my work into this: (look at the output):

Currently my program output is:

enter image description here

My desired output is:

enter image description here

This is my code at the moment:

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 = num - 1;
    int col = num / 2;
    magic[row][col] = 1;

    for (int i = 2; i <= num * num; i++) {
        if (magic[(row + 1) % num][(col + 1) % num] == 0) {
            row = (row + 1) % num;
            col = (col + 1) % num;
        } else {
            row = (row - 1 + num) % num;
            // don't change 
        }
        magic[row][col] = i;
    }

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


}

Guys, Please help me to debug my code, All i need is a little changes that wont totally hurt my code. I think there's something to change in my LOOP but I couldn't find it.

Maybe the mathematically formula..

2

There are 2 answers

1
aparna On

You need to print out in reverse - start from the end. Change your loop traversal condition as shown below

// print results
for (int i = num-1; i >=0; i--) {
    for (int j = num-1; j >=0; j--) {
        System.out.print(magic[i][j] + "\t");
    }
    System.out.println();
}

or keeping the loop variables intact use

    for (int i = 0; i < num; i++) {
        for (int j = 0; j < num; j++) {
            System.out.print(magic[num-i-1][num-j-1] + "\t");
        }
        System.out.println();
    }
3
BevynQ On

first set row to zero

  int row = 0;// instead of num - 1;
  ...

then further down change the way col is updated

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