Puzzle 2D10

Randomly scramble a 2D array

[E-5] Write a function that has two 2D array parameters:

void scramble2D( int rows, int cols, int orig[rows][cols], int scram[rows][cols] )

The function takes each value in orig and places it in a random location in scram.

Of course, scram must contain all the values originally in orig. It has the same values, but with locations scrambled.

#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] )
{
  . . . .
}

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;
}


Previous Page        Answer         Next Page         Home