BeyondProgrammer
BeyondProgrammer

Reputation: 923

Java Random Class output 1 or 0

The result is pretty impressive. with almost 50% each, however the process is the one I am worried about. Sometime i get 10 ones in a roll or 8 zeros in a roll. Which I consider at that period is not a TRUE randomness. I would want to avoid that and only allowing most 3 repeated sequence. Is there a good advice on this?

    int resetOne = 0;
    int resetZero = 0;
    Random ran = new Random();
    while (y < 100) {
        y++;
        x = ran.nextInt(2);
        if (x == 1) {
            resetOne++;
            resetZero = 0;
            if (resetOne == 3) {
                x = ran.nextInt(2);
            }
            oneCounter++;

        } else if (x == 0) {
            resetZero++;
            resetOne = 0;
            if (resetZero == 3) {
                x = ran.nextInt(2);
            }
            zeroCounter++;
        }

        System.out.println(x);
        System.out.println("0 = " + zeroCounter + " " + "1 = " + oneCounter);
    }

Upvotes: 0

Views: 78

Answers (2)

Krease
Krease

Reputation: 16215

As a note before my answer, if I can predict what the next number will be, it's not actually random. In your case, if I get three 0's in a row, I know with 100% certainty that the next number will be a 1.

Now, the simplest way to implement what you're asking is just to introduce two new variables: a counter that gets reset when the result changes, and a cache of the last returned value. If the counter is at the maximum allowed in a row for a result (you got three 0's in a row), then just return the other number and reset the counter (and store this returned value in the lastReturned cache).

This should keep your distributions close to the 50% mark, since it should happen approximately equally for 1s and 0s. It should be easy to test it out to verify.

Upvotes: 1

keshlam
keshlam

Reputation: 8058

True randomness could come up 1 10,000 times in a row. It wouldn't be likely to, but it could. So I would strongly suggest recalibrating your expectations.

If you really want biased randomness -- a progressively less "fair" coin flip -- you'll need to implement that yourself by tracking recent results and adjusting your probabilities.

Upvotes: 2

Related Questions