简体   繁体   中英

Java: Generate a random boolean array with exactly 'x' true - Algorithm

I'm trying to create an algorithm that can generate a boolean array with random booleans given that exactly 'x' amount of the booleans are true. I have solved the algorithm but was curious if there was a cleaner way of doing this.

Below is an example of my work. Two variables, songsToPlay and songsToDownload are randomly generated variables but in this scenario, i have set them to a fixed number 8 and 4, respective. Another important point to mention is that the first boolean value in the array must be true.

Problem: I need to randomly generate an array of 8 true and false values, with exactly 4 of the values being true.

Random ran = new Random();
    int songsToPlay = 8;
    int songsToDl = 4
    Boolean[] ranDownloads = new Boolean[songsToPlay];
    ranDownloads[0] = true;
    int counter = 1; //track how many are true, given the first one is always true.

    for(int i = 1; i < ranDownloads.length; i++) {
            if((songsToDl - counter) >= (ranDownloads.length - i)) {
                ranDownloads[i] = true;
                counter++;
            } else {
                if(counter == songsToDl) {
                    while (i < ranDownloads.length) {
                        ranDownloads[i++] = false;
                    }
                break;
                } else {
                ranDownloads[i] = ran.nextBoolean();
                if(ranDownloads[i] == true) {
                    counter++;                      
                }
                }
            }

    }

I need to randomly generate an array of 8 true and false values, with exactly 4 of the values being true.

This is a variation of a card shuffling problem

List<Boolean> flags = new ArrayList<Boolean>();
for(int i = 0; i < 4; i++) flags.add(true);
for(int i = 0; i < 4; i++) flags.add(false);
Collections.shuffle(flags);

This completes in O(N) time and you can be sure you have the number of true/false you wanted.

Note: all solutions have an equal chance of occurring. The problem with just changing the values until you get the total you want is it is hard to ensure you don't have a bias in the results you produce.

From the JavaDoc for Collections.shuffle(List)

Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.

This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.

This method runs in linear time. If the specified list does not implement the RandomAccess interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a "sequential access" list in place.

随机选择四个数组索引并将它们的内容设置为 true(并确保您不会两次使用相同的索引)。

Given that you use an Object array ( Boolean rather than boolean ), just

  1. fill the first n with Boolean.TRUE and the rest with Boolean.FALSE
  2. do Collections.shuffle(Arrays.asList(yourArray))

And you're all set.

See: Collections.shuffle(list) , Arrays.asList(array)

Why not create a BitSet and randomly flip x bits to 1.

Sample code as requested:

BitSet bs = new BitSet(songCount);

Random random = new Random();
// x: target number of true values
for (int i = 0; bs.cardinality() < x; i++) {
    bs.set(random.nextInt() % songCount);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM