Puzzle 2D11


Reverse the order of the elements in a 2D array

[H-15] Reverse the order of the elements in an MxN array of integers, so that

and so on. For example:

 0  1  2  3  4
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19

becomes

19 18 17 16 15
14 13 12 11 10
 9  8  7  6  5
 4  3  2  1  0

One way to do this is to think in terms of a 2D array and work out which row and column is swapped with which other. Another way is to realize that the elements of the array are stored in linear order and think in terms of swapping the elements of a 1D array.


Here is a testing framework:

#include <stdio.h>
#include <stdlib.h>

#define NUMCOLS 11
#define NUMROWS 4

/* Puzzle D11 -- reverse the order of the elements in a 2D array */

int reverse2D( int nrows, int ncols, int x[nrows][ncols] )
{
  . . . .
}

void print2DArray ( int nrows, int ncols, int x[nrows][ncols] )
{
  int r, c;  /* row and column indexes for the array */

  /* Print elements in row major order */
  for ( r=0; r<nrows; r++ )
  {
    for ( c=0; c<ncols; c++ )
      printf("%3d ", x[r][c]  );
    printf("\n");
  }
}

void fill2DArray ( int nrows, int ncols, int x[nrows][ncols] )
{
  int r, c, val = 0;
  for ( r=0; r<nrows; r++ )
  {
    for ( c=0; c<ncols; c++ )
       x[r][c] = val++ ;
  }
}

int main(int argc, char *argv[])
{
  int x[NUMROWS][NUMCOLS];
  fill2DArray( NUMROWS, NUMCOLS, x );

  printf("Original:\n");
  print2DArray( NUMROWS, NUMCOLS, x );

  printf("\n\nReversed:\n");
  reverse2D( NUMROWS, NUMCOLS, x );
  print2DArray( NUMROWS, NUMCOLS, x );

  return 0;
}


Answer         Next Page         Previous Page Home