yatinsingla
yatinsingla

Reputation: 442

Find repeated cell in 2D array java

I have 3x3 matrix as:

 1 -1 0  0
 1  2 2  1
 1  1 1 -1
-1  0 3  6

I am trying to find the diagonal elements of the cell that has value = -1, and multiplying the diagonal cell ([i-1][j-1],[i-1][j+1],[i+1][j-1],[i+1][j+1]) values with 2. So far I have achieved this but it seems that the cell [1][2] i.e. second row third column,is diagonal to 2 cells, which are [0][1] and [2][3]. So, my resulting array which should look like this:

 1 -1 0  0
 2  2 4  1
 1  2 1 -1
-1  0 6  6

instead looks like this:

 1 -1 0  0
 2  2 8  1
 1  2 1 -1
-1  0 6  6

i.e. there is a value 8 instead of 4 in cell [1][2]. So how can I check if the cell has already visited once and multiplied by 2 so that it cannot be multiplied again. Here is the code that i tried:

for (int i = 0; i <= x; i++) {
        for (int j = 0; j <= y; j++) {
            if (resultArray[i][j] == -1) {
                if (isAdjacent(i - 1, j - 1, x, y))
                    resultArray[i - 1][j - 1] *= 2;
                if (isAdjacent(i - 1, j + 1, x, y))
                    resultArray[i - 1][j + 1] *= 2;
                if (isAdjacent(i + 1, j - 1, x, y))
                    resultArray[i + 1][j - 1] *= 2;
                if (isAdjacent(i + 1, j + 1, x, y))
                    resultArray[i + 1][j + 1] *= 2;
            }
        }
    }
return resultArray;

static boolean isAdjacent(int i, int j, int x, int y) {
    boolean flag = false;
    if (i >= 0 && i <= x && j >= 0 && j <= y) {
        flag = true;
    }
    return flag;

}

Upvotes: 0

Views: 50

Answers (1)

Lincoln White
Lincoln White

Reputation: 649

Make a two dimensional boolean array with true or false at the positions that are diagonal to the -1's and then update the matrix by multiplying all of the numbers at the true positions by two in your matrix. This way no values will be multiplied twice.

So you could initialize the boolean array:

boolean diagonalsArray[][] = new boolean[x][y];

and then instead of multiplying the positions

resultArray[i + 1][j + 1] *= 2;

set those positions to true in your boolean array:

diagonalsArray[i + 1][j + 1] = true;

and between your for loop and return resultArray, do all the multiplying

for (int i = 0; i <= x; i++) {
        for (int j = 0; j <= y; j++) {
               if(diagonalsArray[i][j]){
                    resultArray[i][j] *= 2;
                 }
            }
    }

Upvotes: 1

Related Questions