How to make a choice based on percentage probability

I want to use the answer provided in this to randomly select unique elements from a list.

Following the method described, at each iteration of my loop, I generate a probability value, which is the percentage probability that the current item will be selected from the list.

I need to know how to use this percentage to select an item (or not).

Here is the code that I have, if remainingIndicesthere isList<int>

for (var i = 0; i < remainingIndices.Count; i++)
{
    var probability = pixelsToAdd / (float)(remainingIndices.Count - i);
}

pixelsToAddequal to 120, and remainingIndices.Countequal to 3600. Probability values ​​I start with 0.0333333351

The solution must be flexible to work with a much wider range of values, preferably of any value.

thank

Comment

, , 0 100, 0 1 Random.NextDouble() , .

+5
1

, , [0, 1].

if (Random.NextDouble() <= probability)
    // Take the ith element in the list

:

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--;
    }
}
+3

All Articles