Search code examples
javaarraysalgorithmspiral

algorithm to generate a spiral matrix in java


Write a class that, given a positive integer N, creates and returns a square matrix NxN made out of integers that displays the numbers from 1 to n^2 in a spiral

n=4

In my class I got four methods, three of them are for the direction, while the spiral() method should put every number in the right spot

public static int[][] spiral(int n) {
    int[][] res;
    int i,j;
    int num;
    int direction;

    /** variables initializzazion */
    res=new int[n][n];
    i=0;
    j=0;
    res[i][j]=1;
    direction=0;


    for(num=2; num<=n*n; num++) {
        direction = updateDirection(direction, i, j, n);
        if ((direction==1) || (direction==3))
            i=updateRow(i, direction);
        else
            j=updateColoumn(j, direction);
        res[i][j]=num;
    }
    return res;
}

Sadly, when I try to run it I get an ArrayIndexOutOfBoundException that seems to be caused by the res[i][j]=1;.

How can I fix it so that the Array still starts from 1 and goes up to N*N?

Edit: Added updateDirection() method

to better understand this method have a look at this image:

updateDirection method

public static int updateDirection(int direction, int i, int j, int n) {

    /** if on the secondary diagonal direction is 1 or 3 */
    if(i+j==n-1)
        direction++;
    /** if on the lower half of the main diagonal, direction is 2 */
    if(i==j && j+j>=n)
        direction++;
    /** if on the row below the higher half of the main diagonal, direction is 0 */
    if(i==j+1 && i+j<n)
        direction++;
    /** in other cases, direction doesn't change */

    return direction%4;
    }

Edit2: This is my test method:

public static void testSpiral(){
    for(int n=0; n<=5; n++)
        System.out.println(Arrays.deepToString(spiral(n)));
}

Edit3: updateRow() and updateColoumn() methods added:

public static int updateRow(int i, int direction) {
    int res;
    if(direction==1)
        res=i+1; //moves from top to bottom
    else
        res = i-1; //moves from bottom to top
    return res;
}

public static int updateColoumn(int j, int direction){
    int res;
    if(direction==0)
        res=j+1; //moves from left to right
    else
        res=j-1; //moves from right to left
    return res;

Solution

  • In testSpiral method you are starting the for loop in 0, so the array res is created with size 0.

    When you try to set res[i][j] = 1 you are trying to access the first element in the array but there is none.

    Just start the for in i=1:

    public static void testSpiral(){
        for(int n=1; n<=5; n++)
            System.out.println(Arrays.deepToString(spiral(n)));
    }