I'm trying to understand solution for the following task: Randomly generate a set of M elements from an array of size N. Each element must have equal probability of being chosen.
I found the following solution (I've already read this question, but it does not answer my question):
char[] generateSet(char[] original, int subsetSize) {
char[] subset = new char[subsetSize];
for (int i = 0; i < subsetSize; i++) {
subset[i] = original[i];
}
for (int i = subsetSize; i < original.length; i++) {
int r = rand(0, i);
boolean takeIthElement = r < m;
if (takeIthElement) {
subset[r] = original[i];
}
}
return subset;
}
I think that function does not work correctly. Reasons:
- For example we have an array
{'1', '2', 'a', 'b'}
andm = 2
- Therefore, we should have qual probabilities to generate the following sets:
{1, 2}; {2, 1}; {1, a}; {a, 1}; {1, b}; {b, 1}; {a, 2}; {2, a}; {b, 2}; {2, b}; {a, b}; {b, a}
My concern here is that function will never generate the following sets: {2, 1}; {2, a}; {2, b}
So, it means that it is incorrect.
Aucun commentaire:
Enregistrer un commentaire