faberfix
faberfix

Reputation: 35

How do I replace zeros in a matrix?

Replace the elements with a value of 0.0 with the average of the adjacent elements: previous and / or next in the same row.

Here's my code. Can u help me to solve it?

public void replaceZeros(double[][] array){
    for (int i = 0; i < array.length; i++){
        for(int j = 0; i < array[i].length; j++){
            if(array[i][j] == 0){
                if(array[i][0] == 0){
                    array[i][j] = array[i+1][j];
                } else if(j == array[i].length-1){
                    array[i][j] = array[i-1][j];
                } else {
                    array[i][j] = (array[i+1][j]+array[i-1][j])/2;
                }
            }
        }
    }
}

Upvotes: 3

Views: 218

Answers (2)

Kushal
Kushal

Reputation: 8508

Your for loop had minor issues, below for loop should work :

 public void replaceZeros(double[][] array){
    for (int i = 0; i < array.length; i++){
        for(int j = 0; j < array[i].length; j++){
            if(array[i][j] == 0) { // If element is 0
                if (j == 0) { // If element is in 1st column, any row
                    array[i][j] = array[i][j+1];
                } else if(j == array[i].length-1) { // If element is in last column, any row
                    array[i][j] = array[i][j-1];
                } else { // If element is not in 1st or last column, any row
                    array[i][j] = (array[i][j-1]+array[i][j+1])/2;
                }
            }
        }
    }
}

Upvotes: 1

Max Urbanowicz
Max Urbanowicz

Reputation: 115

If I understand correctly, you want to replace elements of an array that are 0 with the average of a neighbour to the left and right. In the code you provided, you increase and decrease second array argument which is the column. Try this code:

public void replaceZeros(double[][] array) {
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; i < array[i].length; j++) {
            if (array[i][j] == 0) {
                //check if its first element in a row
                if (j == 0) {
                    array[i][j] = array[i][j + 1];
                }
                //check if its last element in a row
                else if (j == array[i].length - 1) {
                    array[i][j] = array[i][j - 1];
                }
                //proceed with calculating average
                else {
                    array[i][j] = (array[i][j + 1] + array[i][j - 1]) / 2;
                }
            }
        }
    }
}

Upvotes: 2

Related Questions