Home > Enterprise >  Reversing a 2D array of objects; Java
Reversing a 2D array of objects; Java

Time:02-03

I need to reverse the objects in a 2D Array

It starts with: {triangle, circle, square}, {star, pentagon, donut}

And should end with: {square, circle, triangle}, {donut, pentagon, star}

Currently it outputs: triangle, circle, square, star, pentagon, donut

I have looked at this question but even copying and pasting working code from that question doesn't work.

Here is the current code I have:

Shape[][] myShapes = {{triangle, circle, square}, {star, pentagon, donut}};

public static void reverseShapes(Shape[][] myShapes) {
    // TO DO #1: Implement your algorithm to reverse myShapes.
    for(int row = 0; row < myShapes.length; row  ){
      
      for(int col = 0; col < myShapes[row].length / 2; col  ) {
        Shape temp = myShapes[row][col];
        myShapes[row][col] = myShapes[row][myShapes[row].length - col - 1];
        myShapes[row][myShapes[row].length - col - 1] = temp;
      }
    }
    
  }//end of reverseShapes

CodePudding user response:

This is how I'd write it:

  public static void reverseShapes(Shape[][] shapes) {
    for(Shape[] row : shapes) {
      for(int left=0, right=row.length-1; left<right; left  , right--) {
        Shape tmp = row[left];
        row[left] = row[right];
        row[right] = tmp;
      }
    }
  }

I think it's much easier to understand with the enhanced for loop syntax pulling a row out at a time, and then the indexed for loop using two different variables, "left" and "right" moving inwards from the ends towards the middle without needing to calculate any indices.

  • Related