reverse the order of the elements in a 2D array
#include <stdio.h>
#include <stdlib.h>
#define NUMCOLS 4
#define NUMROWS 8
/* Puzzle D11 -- reverse the order of the elements in a 2D array */
int reverse2D( int x[][NUMCOLS], int nrows )
{
int r, c;
int temp;
/* Swap elements in the full rows of the first half of */
/* the array with elements in full rows of the last half */
for ( r=0; r<nrows/2; r++ )
for ( c=0; c<NUMCOLS; c++ )
{
temp = x[r][c];
x[r][c] = x[nrows-1-r][NUMCOLS-1-c];
x[nrows-1-r][NUMCOLS-1-c] = temp;
}
/* If there are an odd number of rows, deal with the middle row */
if ( nrows%2 == 1 )
{
r = nrows/2;
for ( c=0; c<NUMCOLS/2; c++ )
{
temp = x[r][c];
x[r][c] = x[nrows-1-r][NUMCOLS-1-c];
x[nrows-1-r][NUMCOLS-1-c] = temp;
}
}
Transpose a matrix
#define NUMCOLS 5
int transpose( int x[NUMCOLS][NUMCOLS] )
{
int r, c, temp ;
for ( r=0; r<NUMCOLS; r++ )
for ( c=0; c<r; c++ )
{
temp
= x[r][c];
x[r][c] = x[c][r];
x[c][r] = temp;
}
Rotate the elements of a 2D array
void rotate2D ( int x[][NUMCOLS], int nrows )
{
int r, c, elmnt00;
elmnt00 = x[0][0];
for ( r=0; r<nrows; r++ )
for ( c=0; c<NUMCOLS; c++ )
if
( c>=1 ) x[r][c-1] = x[r][c];
else if ( r>=1 ) x[r-1][NUMCOLS-1] = x[r][c];
x[nrows-1][NUMCOLS-1] = elmnt00 ;
}
Zero the edges of an Array
/* Puzzle D16 -- Zero the edges of an Array
|
| Change the elements of the outer rows and
| columns of an array to zero. Leave all other
| elements unaffected.
|
*/
int zeroEdges ( int x[][NUMCOLS], int nrows )
{
int j;
/* row 0 */
for ( j=0; j<NUMCOLS; j++ ) x[0][j] = 0;
/* row nrows-1 */
for ( j=0; j<NUMCOLS; j++ ) x[nrows-1][j] = 0;
/* column 0 */
for ( j=0; j<nrows; j++ ) x[j][0] = 0;
/* column NumColumns-1 */
for ( j=0; j<nrows; j++ ) x[j][NUMCOLS-1] = 0;
Count the number of duplicate values in a 2D array of ints
int numberDuplicates( int x[][NUMCOLS], int nrows )
{
int r, c;
/* indexes to the current array element */
int j;
/* index into array[] */
int array[nrows*NUMCOLS];
int duplicateCount = 0;
int inRun = 0;
/* Copy elements from x[][] to array[] */
j = 0;
for ( r=0; r<nrows; r++ )
for ( c=0; c<NUMCOLS; c++ )
array[ j++ ] = x[r][c];
/* Sort the 1D array */
selectionSort( array, nrows*NUMCOLS );
/* Scan the 1D array for duplicates */
for ( j=0; j<nrows*NUMCOLS-1; j++ )
{
if ( !inRun && array[j] == array[j+1] )
{
inRun = 1;
duplicateCount += 2 ;
}
else if ( inRun && array[j] == array[j+1] )
duplicateCount++ ;
else
inRun = 0;
}
return duplicateCount;