Facundo Schiavoni
Facundo Schiavoni

Reputation: 461

Shift all zeros in 2d matrix

I have a 2d array like this:

2 0 0 2 0 4
2 0 0 2 0 4
2 0 0 2 0 4

And I want to shift all the zeros to the left, so for that I made this method:

public static void shiftLeft(int [][] array){

    for (int j = 0; j < array.length; j++) {

        for (int i = 0; i < array.length - 1; i++) {

            if ((array[j][i] != 0) && (array[j][i + 1] == 0)) {
                array[j][i + 1] = array[j][i];
                array[j][i] = 0;
            }
        }
    }
}

But the output I get is this:

0 0 2 0 2 4
0 0 2 0 2 4
0 0 2 0 2 4

How can I make all zeros to go to the left?

Upvotes: 4

Views: 686

Answers (2)

Joachim Huet
Joachim Huet

Reputation: 422

In fact Trugis's answer is also correct but it will just swap the zero with the first non zero. So the order of the numbers will change.

This answer will not change the order of the numbers :

    int[][] A = {   { 2, 3, 4, 2, 4, 4, 5, 0, 0, 0 },
                    { 0, 0, 0, 0, 0, 4, 3, 4, 5, 6 },
                    { 2, 0, 4, 2, 0, 4, 1, 2, 3, 4 }};

    int N = A.length;
    int M = A[0].length;
    int firstZeros = 0;

    for(int i = 0; i < N; i++) { // Loop over the rows 
        for(int j1 = 0; j1 < M; j1++) {
            // If there is a zero we pass by
            if (A[i][j1] == 0 && firstZeros == j1) {
                firstZeros++;
                continue;
            }
            // Otherwise, we have a value so we want to check if there is a zero afterwards
            for(int j2 = j1+1; j2 < M; j2++) {
                // If we find a zero we move it to the left
                if(A[i][j2] == 0) {
                    for (int j3 = j2; j3 > firstZeros; j3--) {
                        // Change zero with previous value
                        A[i][j3] = A[i][j3-1];
                        A[i][j3-1] = 0;
                    }
                    firstZeros++;
                }
            }
        }
        firstZeros = 0;
    }

Upvotes: 0

Stram
Stram

Reputation: 826

In my opinion the easiest way to do this is using 3 nested loops.

Variable i iterates over the rows.

Variable j1 finds the first nonzero element starting from the left of each row.

Variable j2 finds the first zero element after j1 and swaps them. The code below assumes that the bidimensional matrix A was declared as A[N][M], where N and M are respectively the number of rows and number of columns.

for(int i =0;i<N;i++){
  for(int j1=0;j1<M;j1++){
    if (A[i][j1]==0)
      continue;
    for(int j2=j1;j2<M;j2++){
      if( A[i][j2]==0){
         //swap
         int tmp=A[i][j1];
         A[i][j1]=A[i][j2];
         A[i][j2]=tmp;
       }
     }
  }
}

Upvotes: 2

Related Questions