mercredi 20 juillet 2016

logic confusion with rand() in a for loop

I'm trying to do skip-list insertion, so I'm using rand() to determine the level. I know I need to do continuous coin flips, so I figure if I print test counts for the generator it should have approximately 50% less for each successive level. I'm messing up with the logic somehow, but I can't catch my mistake. On the last level it is ~== to the level before it, instead of half.

Here's my code:

#define MAXLEVEL 5
srand(time(NULL));
int newLevel;
int a[6] = {0};
for (int i = 0; i < 100000; i++) {      
    for (newLevel = 0; (rand() < RAND_MAX/2) && (newLevel < MAXLEVEL); newLevel++);
    a[newLevel]++;
}
printf("0: %d   1: %d   2: %d   3: %d   4: %d   5: %d\n", a[0], a[1], a[2], a[3], a[4], a[5]);

And here's the output:

0: 50018   1: 24969   2: 12532   3: 6334   4: 3094   5: 3053

I'm sort of expecting my mistake to be something silly, but I've been looking at this for a while now and can't seem to catch it.




Aucun commentaire:

Enregistrer un commentaire