5

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.

Community
  • 1
  • 1
Steve
  • 695
  • 10
  • 17

1 Answers1

3

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--;
    }
}
Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
  • As is typical I discovered Random.NextDouble() just after submitting the question and it suddenly clicked in my head. Thanks for the solid example though, I'm sure I would have missed something without it. – Steve Feb 02 '13 at 22:03