D20 Answer
/* Puzzle D20 -- fill a 2D array with random ints, without any duplicates
|
| Return 1 if successful, 0 if not. Failure is guaranteed if there
| are fewer integers in the range low..high than there are elements
| in the array.
|
*/
int randomFill2DUnique( int x[][NUMCOLS], int nrows, int low, int high )
{
int r, c, ri, ci;
int unique ;
int trial;
/* Check that the request is possible */
if ( NUMCOLS*nrows > high-low+1 )
return 0;
/* Fill the array in raster order */
for ( r=0; r<nrows; r++ )
for ( c=0; c<NUMCOLS; c++ )
{
/* Find a unique value for the current slot */
unique = 0;
while ( !unique )
{
/* Pick a trial value for the current slot */
trial = randInt( low, high );
unique = 1;
/* Look for the trial in the competed rows */
for ( ri=0; ri<r && unique; ri++ )
for ( ci=0; ci<NUMCOLS && unique; ci++ )
if ( x[ri][ci] == trial ) unique = 0 ;
/* Look for trial in the current row */
for ( ci=0; ci<c && unique; ci++ )
if ( x[r][ci] == trial ) unique = 0 ;
}
/* Fill the slot with a unique value */
x[r][c] = trial ;
}
return 1;
}