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
This is how I'd write it:
I think it's much easier to understand with the enhanced
forloop syntax pulling a row out at a time, and then the indexedforloop using two different variables, "left" and "right" moving inwards from the ends towards the middle without needing to calculate any indices.