JavaNewbie_M107
JavaNewbie_M107

Reputation: 2037

How to generate random booleans in Java using this distribution?

I need to generate some random boolean values.

However, I need to ensure that I get exactly 10 true's in a 100 calls. Also, I need the true values to be pretty much uniformly distributed (for example, the second true will come after 9 false's, the third will come after 7 false's, etc). I tried to implement this using java.util.Random's nextBoolean() method, but it seems the true values get overcrowded in the beginning. Can anyone help?

Upvotes: 1

Views: 684

Answers (4)

ceph3us
ceph3us

Reputation: 7474

little enhanced generic @ted-hopp solution to create distributed prim array of boolean

maybe it will be helpful for someone:

public static boolean[] getRandomBooleanArray(int itemsCount, int truePercentage) {
    Random rand = new Random();
    boolean[] result = new boolean[itemsCount];
    int boolCount = (int) (itemsCount * truePercentage * 0.01); // true items count
    int step = (itemsCount + boolCount - 1) / boolCount; // calculate step
    for (int i = 0; i < boolCount; ++i) {
        int noise = rand.nextInt(step); // calculate noise
        int index = step * i + noise; // initial index
        int realIndex = index < itemsCount ? index : itemsCount-1; // ensure min index
        result[realIndex] = true;
    }
    return result;
}

Upvotes: 0

James
James

Reputation: 8586

If you want truly random exactly K trues out of N, you can create an array of K trues and N-K trues, and use the shuffle method on Collections to randomize.

List<Boolean> values = new ArrayList<Boolean>();
for (int i = 0; i < 10; i++) {
  values.add(true);
}
for (int i = 0; i < 90; i++) {
  values.add(false);
}

Collections.shuffle(values);

If you want it literally spaced out every 10-ish, use Ted's answer, instead, though it's unclear that you'd really want that from your description.

Upvotes: 0

Manidip Sengupta
Manidip Sengupta

Reputation: 3611

Depends how you want to define the randomness ... here is one possibility:

boolean[] ranbool = new boolean[100];
Random rng = new Random();
for (int i = 0 ; i < 10 ; i++)
    ranbool[rng.nextInt(100)] = true;

// Following is redundant

for (int i = 0 ; i < 100 ; i++)
    System.out.print ((ranbool[i]) ? "X" : "O");
System.out.println();

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234847

Here's some code that implements a stratified sampling technique:

boolean[] get10in100() {
    boolean[] result = new boolean[100];
    Random rand = new Random();
    for (int i = 0; i < 10; ++i) {
        result[10 * i + rand.nextInt(10)] = true;
    }
    return result;
}

Upvotes: 4

Related Questions