Answer 2D10
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Puzzle D10 -- scramble arrays */
#define COLS 6
#define ROWS 6
/* Generate a random integer min < = r < = max */
int randInt( int min, int max )
{
return rand()%(max-min+1) + min ;
}
/* scramble a 2D array */
void scramble2D( int rows, int cols, int orig[rows][cols], int scram[rows][cols] )
{
int row, col; /* row and col of original array */
int rs, cs ; /* pair row and col */
int temp;
/* copy the original to the scrambled */
for ( row=0; row<rows; row++ )
for ( col=0; col<cols; col++ )
scram[row][col] = orig[row][col];
/* scramble the scrambled */
for ( row=0; row<rows; row++ )
for ( col=0; col<cols; col++ )
{
rs = randInt( 0, rows-1 );
cs = randInt( 0, cols-1 );
temp = scram[row][col];
scram[row][col] = scram[rs][cs];
scram[rs][cs] = temp;
}
}
void print2DArray ( int nrows, int ncols, int x[nrows][ncols] )
{
int r, c;
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 orig [ROWS][COLS] ;
int scram[ROWS][COLS] ;
srand( time(NULL) );
/* Fill orig with easy to debug values */
fill2DArray( ROWS, COLS, orig );
/* Make the scrambled array*/
scramble2D( ROWS, COLS, orig, scram );
/* Print the arrays */
printf("orig:\n");
print2DArray( ROWS, COLS, orig );
printf("\n\nScrambled:\n");
print2DArray( ROWS, COLS, scram );
printf("\n");
return 0;
}