I was trying to reverse the numbers in this 2D array, but I happened to be reversing only first and the last numbers.
So far I have done this, but don’t know where is the mistake and how to fix it, so that every digits are being reversed, not just first and the last:
int [][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int x = 0, y = array.length - 1; int a = 0, b = array[y - 2].length - 1; int temp; while(x < y && a < b) { temp = array[x][a]; array[x][a] = array[y][b]; array[y][b] = temp; a++; b--; if(a == 3 && b == 0) { a = 0; x++; y--; } } for(int i=0; i<array.length; i++) { for(int j=0; j<array[i].length; j++) { System.out.println(array[i][j]); } }
Advertisement
Answer
Ok, here is another way that doesn’t require using Collections
. It does use Arrays.deepToString()
for displaying the results.
- All reverse methods shown here only require iterating across half the array. This works whether the array has an even or odd number of values.
- first, reverse the array of arrays.
- then during that process, reverse the individual rows, going outside in as the main array is reversed. A helper method reduces code duplication
- If the array is of odd length, call the reverse method once more on the middle array.
- This also works independent of the size of each array.
int[][] array = { { 1, 2, 3, 4, 5 }, { 6, 7, 8 }, { 9 }, { 10, 11, 12 } }; System.out.println("Before: " + Arrays.deepToString(array));
Now the driver code.
int len = array.length; for (int i = 0; i < len / 2; i++) { int[] s = array[i]; array[i] = array[len - i - 1]; array[len - i - 1] = s; reverse(array[i]); reverse(array[len - i - 1]); } if (len % 2 == 1) { reverse(array[len/2]); } System.out.println("After: " + Arrays.deepToString(array));
output
Before: [[1, 2, 3, 4, 5], [6, 7, 8], [9], [10, 11, 12]] After: [[12, 11, 10], [9], [8, 7, 6], [5, 4, 3, 2, 1]]
The helper method.
public static void reverse(int[] v) { int len = v.length; for (int i = 0; i < len / 2; i++) { int t = v[i]; v[i] = v[len - i - 1]; v[len - i - 1] = t; } }