Restricting occurrence of same number in random number generation

• 10-05-2009
teenvista
Restricting occurrence of same number in random number generation
hi,

I use rand() to generate 2 numbers randomly(0 and 1). I want to restrict occurrence of 1 to 10.
I cannot use search algorithm since this will remove all the 1's after 10 1's i want 1's to be randomly distributed across the array(9*9)

Can anyone help me on this?
Thanks
teenvista
• 10-05-2009
laserlight
Keep a count of 1s generated. Once the count hits 10, just fill in the rest with 0s.

EDIT:
Oh wait, that's wrong, since the distribution will not be uniform.

Okay, here's a better try: fill in the array with ten 1s and the rest as 0s. Perform a random shuffle. You're done.
• 10-05-2009
teenvista
how do i do a random shuffle
• 10-05-2009
laserlight
Quote:

Originally Posted by teenvista
how do i do a random shuffle

Unfortunately there is no function available in the C standard library for performing a random shuffle. Search the web for "Fisher–Yates shuffle".
• 10-05-2009
mike_g
Heres an example of how you can do a random shuffle. It could be tweaked to do what you want.

Code:

```#include <stdio.h> #include <stdlib.h> #include <time.h> int main() {     srand(time(NULL));     int i, temp, swap_pos, array[52];     for(i=0; i<52; i++)array[i] = i; //Init     //Shuffle     for(i=51; i>1; i--)     {         swap_pos = rand() % i;    //Pick random location to swap with         temp = array[swap_pos];    //Swap elements         array[swap_pos] = array[i];         array[i] = temp;     }     for(i=0; i<52; i++) printf("%02d\n", array[i]);     return 0; }```
• 10-05-2009
abachler
There are small set size shuffles that are deterministic, and large set shuffles that are non-deterministic. rand() can deterministically shuffle up to about 6 items, or non-deterministically shuffle about 30k items. For larger sets you need to implement some better RNG.