Bonz0
Bonz0

Reputation: 373

Function to set row, column, and diagonal elements in a 2D array given a cell in the array

I need a function with the following signature:

public void requiredFunction(int[][] array, int row, int column) {
    // code
}

The function should increment all the values in the same row, column and diagonal as array[row][column] (except array[row][column] itself).

Suppose I have the following 2D array:

int[][] array = {
    0 0 0 0 0 0
    0 0 0 0 0 0
    0 0 0 0 0 0
    0 0 0 0 0 0
    0 0 0 0 0 0
    0 0 0 0 0 0
};

Now when I call this function with the following values:

requiredFunction(array, 2, 2);

It should convert the array to:

array = {
    1 0 1 0 1 0
    0 1 1 1 0 0
    1 1 0 1 1 1
    0 1 1 1 0 0
    1 0 1 0 1 0
    0 0 1 0 0 1
};

If you think of the array as a chess board, then the function takes the position of the queen (row and column) and increments those places on the chess board, that the queen can move to.

Upvotes: 0

Views: 2354

Answers (2)

giorashc
giorashc

Reputation: 13713

Here is something shorter :

public void requiredFunction(int[][] array, int row, int column) {
  for (int i = 0; i < array.length; ++i) {
      for (int j = 0; j < array[i].length; ++j) {
           if (i == column && j == row)
               continue;
           if (Math.abs(i - column) == Math.abs(j - row) ||
               i - column == 0 || j - row == 0)
               array[i][j]++;                                    
      }
  }
}

Upvotes: 2

LeeNeverGup
LeeNeverGup

Reputation: 1114

First of all, the row and column is easy, say:

public void requiredFunction(int[][] array, int row, int column) {
    //row
    for(int i=0;i<arr.length;i++){
       if(i==col)continue;
       arr[row][i]++;
    }
    //col
    for(int i=0;i<arr[0].length;i++){
       if(i==col)continue;
       arr[i][col]++;
    }
}

For the diagonals, it's a little bit more complicated. You can start from the selected point, and move through the diagonals one by the other. For example, this code:

for(int i=row+1,j=col+1;;++i,++j){
   try{
       arr[i][j]++;
   }catch(IndexOutOfBoundsException e){//the i or j went too far from the board
       break;
   }
}

will increase the values which is in the right-and-down diagonal. Similar loops with --i instead of ++i or --j instead of ++j will do the same for the other diagonals.

EDIT: As commented bellow, it is better to use regular termination condition instead of IndexOutOfBoundsException, so the loop should be:

for(int i = row+1, j = col+1; i <= arr.length && j <= arr[0].length; ++i, ++j){
   arr[i][j]++;
}

Upvotes: 0

Related Questions