Nik Danial
Nik Danial

Reputation: 9

How to create a random number that doesn't repeat?

I have a variable that will either become 1 or 0, and all I know is rand()% 2.

The problem is when I loop it it keeps becoming either 1 for about four times straight then 0, or 0 for straight 6 times then 1.

I want it to be like 0 for once or twice, then 1, then 0 again. Something like that. Is it possible to do this?

Upvotes: 0

Views: 154

Answers (2)

Dave
Dave

Reputation: 46259

If you really want to have only runs of 1 or 2, while maintaining some randomness, you can keep track of it like this;

int nextRandomIshThing( ) {
    static int n1 = 0;
    static int n2 = -1;
    if( n1 != n2 ) {
        n1 = n2;
        // use a high-order bit, which supposedly has better randomness
        // 14 because the standard guarantees that rand() produces at least
        // 15 bits of randomness (not sure why that exactly)
        n2 = (rand( ) >> 14) & 1;
    } else {
        n2 = !n2;
    }
    return n2;
}

http://codepad.org/HTTtPezu

But beware that depending on how you're using this, it means that users can "game" your system; "I've seen 2 1's, therefore the next must be 0!". A truly random source will always produce long sequences. There is a 1 in 8 chance for a truly random source to produce 4 1's or 0's in a row, and a 1 in 16 chance of 5. When you consider that you don't care where exactly the run starts, this becomes even more likely. If you want to be fair, embrace this instead of fighting it!

Oh and don't forget to srand.

Upvotes: 3

Excelcius
Excelcius

Reputation: 1690

You either want a random number or a predictable result. You can't choose the amount of randomness, the whole point of a random number generator is to generate something unpredictable.

But what you can do is simply use the random number in a different way. If you want, say, at most, 4 consecutive runs of 0 or 1 you could determine the count of consecutive numbers using rand and generate the numbers yourself:

int number = 0;
for (int runs = 0; runs < 100; ++runs) {
    int count = rand() % 4;
    for (int i = 0; i < (count ? count : 1); ++i) { // Ensure at least 1 run
        printf("%d", number);
    }
    number = 1 - number;
}

See codepad example: http://codepad.org/OKe5Agib

Upvotes: 3

Related Questions