jeudi 30 avril 2020

Ensure that all 2**N combinations are generated in M random outputs of N booleans

In this example below M = 10 and N = 2, and since M is considerably larger than N, the probability is that every possible combination of N booleans, (True, True), (True False), (False, True), (False, False) in this example, will be generated among the M outputs at least once, as has occurred below.

for _ in range(10):
...     choice1 = np.random.choice((True, False))
...     choice2 = np.random.choice((True, False))
...     print(choice1, choice2)
...     
False False
False False
True False
True False
True True
False True
True True
True True
True False
False False

But it isn't guaranteed. There is a low probability of getting 10 X (False, False) or alternatively 10 X (True, True), or perhaps a mix where one particular pair, say (False, True), never appears.

In 'real life' the print is replaced by a yield statement, and choice1 and choice2 are accompanied by several other randomly generated numeric variables.

How could I easily change the generation of choice1 and choice2 to make sure they always cover all of the 4 possibilities, while still keeping it (mostly) random, without just adding 4 extra non-random cases to force them to occur?

I feel as if the selection without replacement option could be exploited, but I can't think how to incorporate this.




Aucun commentaire:

Enregistrer un commentaire