0

I have been working on Magic Square formation, after reading through the algo, I found out there are certain set of rules to be followed while forming the MagicSquare.

The algo which I'm following is :

  1. The magic constant will always be equal to n(n^2 + 1)/2, where n is the dimension given.
  2. Numbers which magicSquare consists will always be equals 1 to n*n.
  3. For the first element that is 1, will always be in the position (n/2, n-1).
  4. Other elements will be placed like (i--,j++)
  5. The condition to be put through for placing an elements are :

    a) If i < 0, then i = n-1.
    b) If j == n, then j = 0.
    c) This is a special case, if i < 0 and j=n happens at the same time, then i = 0, j = n-2.
    d) If the position is already occupied by some other element, then i++, j = j-2.
    
  6. Then input the element inside the magicSquare based upon the conditions.

Based upon the above algo, I have written down a code, and due to some reason I'm getting

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3                                                                  
        at Main.generateMagicSquare(Main.java:25)                                                                                       
        at Main.main(Main.java:58) 

This is weird. I have checked, and feels like it is safe to use the code to get the desired result, but I don't know where I'm going wrong.

Code

static void generateMagicSquare(int n){
    int[][] magicSquare = new int[n][n];

    //initialising for pos of the elem 1
    int i = n/2, j = n-1;
    magicSquare[i][j] = 1;

    //the element consist by the magic square will always be equal to 1 to n*n
    for(int num=2; num <= n*n; num++){
        //it must go like this, for any other element
        i--; j++;

        // if the element is already present
        if(magicSquare[i][j] != 0){
            i++;
            j -= 2; 
        }else{
            if(i < 0)
                i = n-1;

            if(j == n)
                j = 0;

            if(i < 0 && j == n){
                i = 0;
                j = n-2;
            }
        }

        magicSquare[i][j] = num;
    }

    for(int k=0; k<n; k++){
        for(int l=0; l<n; l++){
            System.out.print(magicSquare[k][l] + " ");
        }

        System.out.println();
    }
}

Any help would be appreciated. Thanks. Since I could have copied and pasted the code from internet, but I want to learn it in my way, and your help would help me achieve what I want. :)

EDITS

After reading through the exception, I made some amendments in my code, but still some of the result didn't come upto the mark.

Here is my updated code =======>

static void generateMagicSquare(int n){
int[][] magicSquare = new int[n][n];

//initialising for pos of the elem 1
int i = n/2, j = n-1;
magicSquare[i][j] = 1;

//the element consist by the magic square will always be equal to 1 to n*n
for(int num=2; num <= n*n; num++){
    //it must go like this, for any other element
    i--; j++;

    if(i < 0){
       i = n-1;
    }

    if(j == n){
       j = 0;
    }

    if(i < 0 && j == n){
       i = 0;
       j = n-2;
    }

    if(magicSquare[i][j] != 0){
       i++;
       j -= 2;
    }else{
       magicSquare[i][j] = num;
    }
}

for(int k=0; k<n; k++){
    for(int l=0; l<n; l++){
        System.out.print(magicSquare[k][l] + " ");
    }

    System.out.println();
}
}

I get this output :

2 0 6                                                                                                                                   
9 5 1                                                                                                                                   
7 3 0 

Still not the right answer to follow.

Alok
  • 8,452
  • 13
  • 55
  • 93
  • 5
    start with the beginning: do you know what that error message means? – Stultuske Jan 29 '19 at 11:08
  • I assume you write in some kind of IDE (NetBeans? Eclipse? IntelliJ?). That has debugging tools inside it. Look up how to use those, it makes a world of difference in solving problems such as what you have here. – M. Prokhorov Jan 29 '19 at 11:17
  • No I write code on the online Java compiler. I'm working on my code right now. Got the point what @Stultuske said to me. – Alok Jan 29 '19 at 11:18
  • @Stultuske I have added the edits, please see. – Alok Jan 29 '19 at 11:47

2 Answers2

1

This line throws the error:

if(magicSquare[i][j] != 0)

and the problem is that the array magicSquare is initialized as:

int[][] magicSquare = new int[n][n];

meaning that it has n columns with indexes from 0 to n - 1 (indexes are zero based).
The variable j is initialized as

j = n-1;

and later this line:

j++;

makes j equal to n
so when you access magicSquare[i][j] you are trying to access magicSquare[i][n]
which does not exist.

forpas
  • 160,666
  • 10
  • 38
  • 76
  • I have edited the code, but somehow I'm getting 0 as the value. Please check my `Edits`. Now, no exception in my code. – Alok Jan 29 '19 at 11:47
0

The index of an array is an integer value that has value in interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception. You have to check the value of i and j before using it in array. You can use the below code :

for(int num=2; num <= n*n; num++){
        i--; j++;
        //Here We have to check the value of i and j i.e. it should less than or equal to the length of array.
        if((i <= magicSquare[0].length-1 && j <= magicSquare[0].length-1))
        {
            if(magicSquare[i][j] != 0){
                i++;
                j -= 2; 
            }else{
                if(i < 0)
                    i = n-1;
                if(j == n)
                    j = 0;
                if(i < 0 && j == n){
                    i = 0;
                    j = n-2;
                }
            }
            magicSquare[i][j] = num;
        }
    }

For understanding ArrayIndexOutOfBoundsException, Please visit :

https://www.geeksforgeeks.org/understanding-array-indexoutofbounds-exception-in-java/

Bishal Dubey
  • 150
  • 7
  • Thanks for the input, but your code outputs the incorrect values of the `magicSquare`. – Alok Jan 29 '19 at 11:36
  • As you mentioned about the ArrayIndexOutOfBoundsException, i just resolved that only. For magicSquare, you have to code right!! – Bishal Dubey Jan 29 '19 at 11:45