Phil CK

Rand Weirdness

Last updated on

I know rand() has issues, but I didn’t realize this would happen. I wanted to select a string at random, I had 7 strings, so I did the usual thing seed rand from time, but I kept getting the same result.

#include <time.h>
#include <stdlib.h>
#include <stdio.h>


int
main() {
        const char *strs[] = {
                "1",
                "2",
                "3",
                "4",
                "5",
                "6",
                "7",
                /*"8",*/
        };

        srand(time(NULL));

        int i;
        for(i = 0; i < 8; ++i) {
                int idx = rand() % (sizeof(strs) / sizeof(strs[0]));
                printf("%s,", strs[idx]);
        }
        printf("\b\n");

        return 0;
}

build and go

cc rand_test.c && ./a.out

Results

It always starts with 6.

6,5,3,6,7,5,7,7
6,5,3,6,7,5,7,7
6,5,4,4,6,4,2,7
6,5,4,4,6,4,2,7
6,5,5,3,4,3,4,1
6,4,3,4,5,5,4,2
^ -- over 50 runs of the program and its always 6.

If I add another string to the array I get this.

8,6,2,4,8,2,7,6
7,7,4,6,2,2,7,4
6,8,6,1,5,2,7,3
6,8,6,1,5,2,7,3
5,1,7,3,7,2,8,2
5,1,7,3,7,2,8,2

Which is alot more random. Also if I reduce the number of strs I will get a similar result. There is something with this implimentations rand() that makes 7 strs very predictable. Other impls will produce different results.