Reputation: 33
I have a 2d array :
1 0 1 1
1 1 1 1
1 1 1 1
1 1 1 1
I have to write a program that checks if there is a 0 in the array and if so replace the row and column with 0's so it looks like this after :
0 0 0 0
1 0 1 1
1 0 1 1
1 0 1 1
This is my code so far :
public class Run {
public static void main(String[] args){
//defining 2d array
int[][] m = { {1,0,1,1},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1}};
int[][] newArray = zero(m);
//looping through the array to get rows and columns for the array
//rows
for (int i = 0; i < m.length; i++) {
//columns
for (int j = 0; j < m[0].length; j++) {
//check if the integer is the last in the row
if(j== m.length-1){
//print the rows and columns of the array(no space)
System.out.print(newArray[i][j]);
}else{
//print the rows and columns of the array(w/ space)
System.out.print(newArray[i][j] + " ");
}
}
//new line for the new row
System.out.println("");
}
}
//checks if there is a zero in the row
public static int[][] zero(int[][] m) {
//defining row length and column length
int rows = m.length;
int columns = m[0].length;
int[][] tempArray = m;
//looping through the array to get rows and columns
//rows
for (int i = 0; i < rows; i++) {
//columns
for (int j = 0; j < columns; j++) {
//if the number is 0 loop through that row and column again and change everything to 0
if(m[i][j] == 0){
//columns in that row
for(int l = 0; l < rows; l++)
{
tempArray[l][j] = 0;
}
//rows in that column
for(int l = 0; l < columns; l++)
{
tempArray[i][l] = 0;
}
}
}
}
//returning the updated array
return tempArray;
}
}
when I run my code it returns :
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
but when I take out either :
//columns in that row
for(int l = 0; l < rows; l++)
{
tempArray[l][j] = 0;
}
or
//rows in that column
for(int l = 0; l < rows; l++)
{
tempArray[l][j] = 0;
}
it returns :
0 0 0 0
1 1 1 1
1 1 1 1
1 1 1 1
or
1 0 1 1
1 0 1 1
1 0 1 1
1 0 1 1
Upvotes: 3
Views: 8286
Reputation: 29265
You detect 0 in a loop, then go and modify the data and continue your loop which is now going to see more zeros and so set even more zeros.
You should either break once you've spotted a 0, or split the detection and "rewriting" - do all the detection first then all of the rewriting.
Upvotes: 1
Reputation: 37645
The problem is the line
int[][] tempArray = m;
This makes tempArray
and m
the exact same instance, so you only actually have one matrix.
Instead you should do
int[][] tempArray = new int[rows][columns];
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
tempArray[i][j] = m[i][j];
Upvotes: 2