質問

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.

他のヒント

Choose four of the array indexes randomly and set their content to true (and make sure that you don't use the same index twice).

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);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top