/* Puzzle C46 -- randomly scramble the elements in an array */ void scrambleArray( int arr[], int size ) { int j, twin; /* element j and its twin are swapped */ int twinVal; /* for each element j, pick a random twin and swap */ for ( j=0; j<size-1; j++ ) { twin = randInt(j,size-1); twinVal = arr[twin]; arr[twin] = arr[j]; arr[j] = twinVal; } }
Comments: The scrambleArray()
function first randomly picks
one of the size
elements of the array to place in the first slot. Then for the
second slot it randomly picks one of the remaining size-1
elements, for
the third slot one of the remaining size-2
elements, and so on.
Of course, it does this in a loop. To put a value into the current slot, swap
the value originally in the slot with the value to be placed there. The so-far
unpicked values are all to the right of the current slot, so to pick a value
for the current slot j
generate a random number from j
to size-1
.