Skip to content
Advertisement

Reversing digits in 2D array

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:

JavaScript

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.
JavaScript

Now the driver code.

JavaScript

output

JavaScript

The helper method.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement