Originally Posted by
keira
Say you need all the numbers between 1 and 26 in a random order (no repeats). What's the best way to go about doing that? I can think of some extremely inefficient ways...
Fill an array with the values 1..26 and then "shuffle" it somehow. Try Googling for "random shuffle." It's easy to make a mistake and cause the shuffle to be not-quite-random, so be careful.
If it were me, I'd do the following:
Code:
int array[26] = { 0 }; /* Initialize array to all zeros */
int i;
int index;
for(i = 1; i <= 26; i++)
{
do
{
index = rand() % 26; /* Random position between 0 and 25 */
} while(array[index] > 0);
array[index] = i;
}
Basically, this loops through all the values 1..26 and selects a random spot in the array to put that value. It uses the special value 0 to mean, "No value here." If there is already some other value at that spot, i.e., if there is a non-zero value at that index, it loops, trying random indexes until it finds an unfilled spot.
There are other ways, of course.