Hello:

I was looking for shuffling algorythms and found some in the PAQ. I also found something called the Fisher-Yates Shuffle in some perl docs. Problem is that, more than implementations, I would like explanations on how they work. You see, I know they work, I can see them work, but I seem to be pretty dense in these matters and get lost when someone starts talking about permutations and n!..... could someone please explain in details the inner workings and theory behind a simple shuffle like:

/* Taken from from Ozo's answer, PAQ Q.10060202 */

for( i=1; i<sizeof(array)/sizeof(array[0]); i+= 1 ){

int r = random()%(i+1);

int temp = array[i]; array[i] = array[r]; array[r] = temp;

}

TIA,

-dZ.

The assumption is that the elements of array contain "representations" of the cards in the deck (or whatever you are shuffling.

for( i=1; i<sizeof(array)/sizeof(arr

// sizeof(array) will result in the total number of bytes in the array

// sizeof(array[0]) will result in the number of bytes in the first element

// thus sizeof(array)/sizeof(array

// i.e. it is a general way of setting the number of iterations

int r = random()%(i+1);

//random() (or the more standard rand() return

// a pseudo-random number in the range 0 - RAND_MAX

// by modding it with i+1 you will get a number from 0 to i

int temp = array[i]; array[i] = array[r]; array[r] = temp;

// shuffle: take the "next" "card" (in array[i])

// and swap it with the card in array[r]

}