Challengeprobability based selection

time to read 2 min | 223 words

Here is an interesting problem that I just run into. I need to select a value from a (small) set based on percentage. That seems like it would be simple, but for some reason I can’t figure out an elegant way of doing this.

Here is my current solution:

var chances = new Page[100];
int index = 0;
foreach (var page in pages)
{
    for (int i = index; i < index + page.PercentageToShow; i++)
    {
        chances[i] = row;
    }
    index += page.PercentageToShow;
}
return chances[new Random().Next(0, 100)];

This satisfy the requirement, but it is… not as elegant as I would wish it to be.

I may have N number of values, for small N. There isn’t any limitation on the percentage allocation, so we may have (50%, 10%, 12%, 28%). We are assured that the numbers will always match to a 100.

More posts in "Challenge" series:

  1. (03 Jan 2020) Spot the bug in the stream–answer
  2. (15 Feb 2010) Where is the optimization?