Reputation: 715
I wish to use the answer provided in this post to randomly choose unique items from a list.
Following the method described, in each iteration of my loop I generate a probability value which is the percentage chance of the current item being picked from the list.
What I need to know is how do I use this percentage value to pick the item (or not).
Here is the code I have, with remainingIndices
being a List<int>
for (var i = 0; i < remainingIndices.Count; i++)
{
var probability = pixelsToAdd / (float)(remainingIndices.Count - i);
}
pixelsToAdd
is 120 and remainingIndices.Count
is 3600.
The probability values I am getting start at 0.0333333351
The solution should be flexible to work with a much wider range of values, preferably any values.
Thanks
Comment
For future readers of this question I should clarify that at first I thought the probability value was some percentage between 0 and 100 but in reality it's a value between 0 and 1 and so matches up perfectly with the return value of Random.NextDouble()
which therefore can be used for comparison as described in the answers below.
Upvotes: 5
Views: 2924
Reputation: 13022
To use your probability, compare it with a sample from random variable following a uniform distribution on [0, 1]
.
if (Random.NextDouble() <= probability)
// Take the ith element in the list
You resulting loop will be:
List<???> selectedItems = new List<???>();
for (var i = 0; i < remainingIndices.Count; i++)
{
var probability = pixelsToAdd / (float)(remainingIndices.Count - i);
if (Random.NextDouble() <= probability)
{
selectedItems.Add(items[i]);
pixelsToAdd--;
}
}
Upvotes: 3