Ironman131
Ironman131

Reputation: 13

Making a border of numbers in descending order in matrix

I am trying to make a border around an empty matrix that is ascending and descending. I already have the top and left side which are ascending from 0 to 4, but I cannot get the right side and bottom side to go from 4 to 0. Here is the code of my for loops. I have tried about every variation to get it to work, but it either gives me an index out of bounds exception or just shows up as zeroes instead. I would greatly appreciate any feedback.

private static void fillBorder( int[][] matrix )
{
   for (int r=0; r<matrix.length; ++r) // left side
   {
        matrix[r][0] = r; 
   }
   for (int j=0 ; j<matrix.length; ++j) // top
   {
        matrix[0][j] = j;
   }
   for (int m=matrix.length; m>0; --m) // bottom
   {
        matrix[4][m] = m;
   }
   for (int s=matrix.length; s>0; --s) // right side
   {
        matrix[s][4] = s;
   }

}

Here is also a picture of what the output is supposed to look like to give you a better idea of what it's supposed to be. picture of output

enter image description here

Upvotes: 1

Views: 453

Answers (2)

ControlAltDel
ControlAltDel

Reputation: 35011

For your rows, you should be using matrix[0].length. The other thing is you should use the matrix dimension rather than hardcoding 4 into the code

   private static void fillBorder( int[][] matrix )
    {
       for (int r=0; r<matrix.length; ++r) // left side
       {
            matrix[r][0] = r; 
       }
       for (int j=0 ; j<matrix[0].length; ++j) // top
       {
            matrix[0][j] = j;
       }
       for (int m=matrix[0].length; m>0; --m) // bottom
       {
            matrix[matrix.length - 1][m] = m;
       }
       for (int s=matrix.length; s>0; --s) // right side
       {
            matrix[s][matrix[0].length - 1] = s;
       }

    }

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521437

I think you can do this with a single for loop:

for (int i=0; i < matrix.length; ++i) {
    matrix[0][i] = i;
    matrix[i][0] = i;
    matrix[matrix.length-1][matrix.length-1-i] = i;
    matrix[matrix.length-1-i][matrix.length-1] = i;
}

This assumes that the matrix in fact is square (i.e. has the same number of rows and columns). If not, then my code would have to change, but then again so would your problem statement.

for (int r=0; r < matrix.length; ++r) {
    for (int c=0; c < matrix.length; ++c) {
        System.out.print(matrix[r][c] + " ");
    }
    System.out.println();
}

Output:

0 1 2 3 4
1 0 0 0 3
2 0 0 0 2
3 0 0 0 1
4 3 2 1 0

Upvotes: 1

Related Questions