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; }
Comment: Notice the tricky code dealing with the start of a run:
if ( !inRun && array[j] == array[j+1] )
The start of a run is detected when the first
two elements of it are found to be the same.
The duplicateCount
must be incremented by two.
In the middle of a run,
else if ( inRun && array[j] == array[j+1] )
duplicateCount
is incremented by only
one for each new element in the run.
Of course, when not in a run, duplicateCount
is not incremented at all.