laetee
laetee

Reputation: 41

How to alternate the order of elements in every other column in a 2D Array

An empty 2D array a should be filled with the following values:

1 8 9 16 17
2 7 10 15 18
3 6 11 14 19
4 5 12 13 20

I've been having a lot of trouble with figuring out how to reverse the order of a column. This is the closest I've gotten:

int [][] a = new int[4][5];
        int count = 1;
        for(int c = 0; c < a[0].length; c++) {
            for(int r = 0; r < a.length; r++) {
                a[r][c] = count;
                count++;
            if(r% 2 == 0 && c % 2 != 0) {
                count = 20;
                a[r][c] = 20;
                count--;
           }    
       }
}

Upvotes: 0

Views: 245

Answers (2)

Angel Koh
Angel Koh

Reputation: 13485

you are on the right track, just reverse the row when inserting even numbered columns.

 public static void main(String []args){  

    int count =1;
    int columnCount =5;
    int rowCount = 4;

    int [][] a = new int[rowCount][columnCount];


    for (int column = 0; column<columnCount; column ++ ) {
        for (int row = 0; row <rowCount; row ++) { 

          if(column%2==0){
              a[row][column] = count; 
          }else {
              a[rowCount-row-1][column] =count;
          }
          count ++ ;
        }     
    }   

    //validate results 
    for (int row = 0; row <rowCount; row ++) { 
        for (int column = 0; column<columnCount; column ++ ) { 
            System.out.print (a[row][column] +" ");
        }
        System.out.println();
    }

 }

this will give you the following results

$java -Xmx128M -Xms16M HelloWorld
1 8 9 16 17 
2 7 10 15 18 
3 6 11 14 19 
4 5 12 13 20 

Upvotes: 1

Mohsen_Fatemi
Mohsen_Fatemi

Reputation: 3391

You should define a variable that defines the direction you want to move at each iteration, i've named it sign. if sign is positive, column will be filled in a downward manner, otherwise it would move in the opposite direction.

int [][] a = new int[4][5];
int count = 1;
int sign = 1;
for(int j = 0 ; j < 5 ; j++){
    if(sign==1)
        for(int i = 0 ; i < 4 ; i++){
            a[i][j]=count;
            count++;
        }
    else
        for(int i = 3 ; i >=0 ; i--){
            a[i][j]=count;
            count++;
        }
    sign *= -1;
}

If we want to print the array we'll have :

for(int i = 0 ; i < 4; i++){
        for(int j = 0 ; j < 5; j++)
            System.out.print(a[i][j]+"\t");
        System.out.println();
    }

Resulting output would be :

1   8   9   16  17  
2   7   10  15  18  
3   6   11  14  19  
4   5   12  13  20  

Upvotes: 1

Related Questions