I've used an algorithm called the "Fischer-Yates" shuffle alot for randomizing arrays. It (or my version) works like this:
- loop backward through the array, from the last element to the 3rd element, ie:
Code:
int i, len = /* array length */
for (i=len; i>1; i--)
- at each iteration, generate a random number (x) from 0 to the number of the current element (i):
- if x == i, continue, otherwise, swap element i with element x.
That's about a half dozen lines. Remember: If you don't want the results to always be the same when you run the program, use srand(time(NULL)) once in main() before the shuffle is first executed.
There's a slight imbalance in the algorithm in that elements at the end of the array have a greater chance of not being moved than elements at the beginning. If you wanted to resolve that, you could make x = rand()%len (but this actually decreases the overall randomness by creating the chance that previously shuffled elements could be swapped back) or run once forward and once backward. In practice, neither of those is necessary. Try it a few times -- the result is always a pretty thorough looking shuffle.