Mirroring images is a simple and widely applicable tool. You've probably done it in your own designs. Car designers at GM Research Labs even use the idea of it -- they sculpt half the car out of clay, and then use a mirror to show what the whole car would look like. If they have a digital mirror, they can make the actual second half of the real thing totally symmetrical.
Today, you'll figure out how to write a method that flips pictures. But wait! We're not just flipping the whole thing backwards. That's boring. We're going to keep one half constant, and then make the other half a mirror of the first side. See Figure 6 for an example:
Can you figure out the algorithm for this process? Test your algorithm on different sizes of two- dimensional arrays of integers. Will it work for 2D arrays with an odd number of columns? Will it work for 2D arrays with an even number of columns?
One algorithm is to loop through all the rows and half the columns. You need to get a pixel from the left side of the picture and a pixel from the right side of the picture, which is the same distance from the right end as the left pixel is from the left end. Set the color of the right pixel to the color of the left pixel. The column number at the right end is the number of columns, also known as the width, minus one. So assuming there are at least 3 pixels in a row, the first left pixel will be at row=0, col=0 and the first right pixel will be at row=0, col=width-1. The second left pixel will be at row=0, col=1 and the corresponding right pixel will be at row=0, col=width-1-1. The third left pixel will be at row=0, col=2 and its right pixel will be at row=0, col=width-1-2. Each time the left pixel is at (current row value, current column value), the corresponding right pixel is at (current row value, width - 1 - (current column value)).
The following method implements this algorithm. Note that, because the method is not looping through all the pixels, it cannot use a nested for-each loop.