Write a method to randomly generate a set of m integers from an array of size n. Each element must have equal probability of being chosen.
This is a fairly well known question - featured in multiple books and interviews - but either I am not reading the question correctly, or to me the requirements of this question cannot actually all be fulfilled at the same time in Java.
Let's say have an array of size n=3
Integer[] ar = {1,1,5}
if w chose m=2 for our randomly generated set, I don't see how we can guarantee an equal probability for each element to be chosen.
In other words, asking for a Java set of 2 integers from the given array of size 3 makes it impossible to ensure an equal probability for each element. To illustrate, if we call the [0] a, [1] b, [2] c, then the all the 2 element combinations chosen at random, with removal, will look like this:
- ab
- ba
- ac
- bc
- ca
- cb
Since choices 1) and 2) would automatically invalidate a unique element requirement of a set in Java, in this particular situation element 'c' i.e. number 5 will always end up with a probability of 100% if we are to end up with a set of 2 elements.
I guess it is even easier to illustrate this issue if the array contains only duplicates i.e. {1,1,1}, and then a set of m=2 integers would simply be impossible.
Is there something I am misreading or misinterpreting with regards to this question.
Aucun commentaire:
Enregistrer un commentaire