0

I am creating a magicsquare in java and have been given the following pseudocode:

> Create a 2 dimensional array of size n by n and set all values to be 0
Set x = 1, y = (n+1)/2 (row 1 and column (n+1)/2 ).
Insert 1 at x, y
  for i = 2 to n^2 do
   if element x − 1,y − 1 is empty (i.e. = 0) then
     x = x − 1, y = y − 1
   else
     x = x + 1, y = y
   end if
  Insert i at x, y
end for

My code is this:

class main1 {

    static void squarematrix(int n) {

        int[][] magicsquare = new int[n][n];
        
        int x = 1; //row
        int y = ((n+1)/2); //column

        magicsquare[x][y] = 1; //inserting 1 and (1, 5)

        for (int i = 2; i < (n*n); i++) {
            System.out.println(i);
            System.out.println(x);
            System.out.println(y);
            if (magicsquare[x-1][y-1] == 0) {
                x = x-1;
                y = y-1;
            } else {
                x = x+1;
                y = y;
            }

            magicsquare[x][y] = i;
        }

I understand that the x value goes lower than 0 giving me the out of bounds error, but I am honestly unsure how to fix it. Any help would be great thank you.

HoRn
  • 1,458
  • 5
  • 20
  • 25
  • 1
    The problem is not with your code it's with the pseudocode you were given. As written it will immediately walk off the edge of the array. There's something missing there. If the algorithm is supposed to be something like the one at https://www.geeksforgeeks.org/magic-square/ then the pseudocode is missing logic for wrapping around the square. – sprinter Aug 17 '22 at 22:56
  • @sprinter i messaged the teacher, and they said, yes, we were supposed to know it would already wrap around the edge of the square, so that it goes to the end of the array. But, I am confused on how to go about doing that. Would i just have two if functions checking if x or y < 0, then change the x or y value to the length of the 2d array. Thank you for the help – asad islam Aug 19 '22 at 11:18
  • Yes that's write - you check if x|y < 0 and that x|y >= n. You can also use a modulo operator: `x = (x + n) % n` – sprinter Aug 22 '22 at 01:23

0 Answers0