Ayende @ Rahien

It's a girl

Challenge: probability based selection

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.

Comments

Rafal
03/24/2009 02:41 PM by
Rafal

Look at roulette wheel selection for genetic algorithms. But I haven't seen any significantly better implementation.

Brian
03/24/2009 02:58 PM by
Brian

Maybe I'm missing the something, but aren't you just finding the page that has a percentage range (offset by the sum of previous percentages) in which a random number falls? If so, you should be able to remove at least one loop.

Remco Ros
03/24/2009 03:15 PM by
Remco Ros

how about:

var pagesperc = new Dictionary <page,> ();

int total = 0;

foreach(var page in pages)

{

pagesperc.Add(page, page.PercentageToShow + total)

total += page.PercentageToShow;

}

int rnd = new Random().Next(0, 100);

foreach(var kv in pagesperc)

{

if (kv.Value == rnd)

{

    return kv.Key

}

}

Remco Ros
03/24/2009 03:16 PM by
Remco Ros

Sorry, comment messed up.

The dictionary should be generic {Page, int}

Brian
03/24/2009 03:19 PM by
Brian

@Remco at that point, why don't you just put the random number selection before the first loop and do away with the second loop entirely?

Ayende Rahien
03/24/2009 03:20 PM by
Ayende Rahien

I don't understand how this is suppose to work.

Let us assume that you have 50% / 50%.

And random returns 7.

Brian
03/24/2009 03:32 PM by
Brian

Maybe the one loop approach (you'd have to use a different first loop then Remco) isn't more elegant, just thought you might be looking at the problem backwards.

Adam
03/24/2009 03:34 PM by
Adam

I'm not sure about the language, but wouldn't this work?

int index = new Random().Next(0, 100);

foreach (var page in pages)

{

if (index < page.PercentageToShow) return page;

index -= page.PercentageToShow;

}

?

Remco Ros
03/24/2009 03:37 PM by
Remco Ros

@Ayende

sorry, didn't test it.

This should work:

replace the last loop with:

        foreach (var kv in pagesperc)

        {

            if (number <= kv.Value)

            {

                foundpage = kv.Key;

                break;

            }

        }
Peter Morris
03/24/2009 03:56 PM by
Peter Morris

Importantly

1: It's fast enough

2: It's very easy to understand

3: It works

So I wouldn't change it.

Matt
03/24/2009 04:04 PM by
Matt

int rand = new Random().Next(0, 100);

int percentSoFar = 0;

foreach (var page in pages)

{

percentSoFar += page.PercentageToShow;

if (percentSoFar >= rand) return page;

}

// error?

Remco Ros
03/24/2009 04:10 PM by
Remco Ros

@Matt

that works too ! nice one.

innesm
03/24/2009 04:25 PM by
innesm

You could iterate through the pages and for each page generate a boolean value from the weighted probability of that page being selected (the 'percent' of the page over the 'percent' of all remaining pages including the page). If that value is true, return the page.

Eg If you get to the last page, the probability will be 1.0 that you return that page.

Peter Morris
03/24/2009 04:31 PM by
Peter Morris

Matt, I tried that too but with 2 pages (10% and 20%) I didn't get anything near a 2 to 1 ratio, more of an 8 to 1.

innesm
03/24/2009 04:39 PM by
innesm

Pseudocode:

percent = 100.0

for each page in pages {

if testprobability(page.percent / percent)

return page

percent -= page.percent

}

bool testprobability(probability) {

// return true if random between 0 and 1.0 is less than probability

}

sample:

page1 20% probability == 20/100

page2 50% probability == 50/80

page3 30% probability == 30/30

Brian
03/24/2009 04:40 PM by
Brian

@Peter - 10 + 20 != 100.

"We are assured that the numbers will always match to a 100."

Yann Schwartz
03/24/2009 04:48 PM by
Yann Schwartz

This reminds me of my probability vectors when playing with Markov Chains. There are several ways, when you don't have a lot of items in your array, best way is to use some kind of sparse array

int rnd = new Random().Next(0, 100);

pages.SkipWhile(p => p.PercentageToShow < limit).Take(1);

Note: percentage to show is actually a weighted percentage ( p.Percentage + every p.Percentage less than that. If you want to stick to absolute percentage, you have to massage your collection first, with a loop, a aggregate of some sort and a sort)

Peter Morris
03/24/2009 04:49 PM by
Peter Morris

Brian, 100 is irrelevant, the code is functionally identical whether they add up to 100, 30, or 99. The ratio should still be 2 to 1.

Yann Schwartz
03/24/2009 04:51 PM by
Yann Schwartz

(continued)

read rnd instead of limit

int rnd = new Random().Next(0, 100);

pages.SkipWhile(p => p.PercentageToShow < rnd).Take(1);

your weights must be ordered ascending, and it must be weights, not absolute pc. Going from absolutes to weighted percentages is trivial and could be done ahead of time, once and for all.

FallenGameR
03/24/2009 04:56 PM by
FallenGameR

I have had a similar issue. There was a dictionary of elements (T) and there was a probability of choosing each element (double) [Dictionary <t,> Weights]:

// Make sure that summ of probabilities = 1.0

Normalize( );

// All weights are on single tape with length 1.0

// Tape is divided by regions whose length equals to their probability

// Revolve the rulette and stop somewhere on the tape

double rouletteStop = Random.NextDouble( );

// Search for element that we stopped at

T lastElement = default( T );

foreach( T key in Weights.Keys )

{

lastElement = key;

rouletteStop -= Weights[ key ];

if( rouletteStop <= 0.0 )

{

    return lastElement;

}

}

// We are at the end of the tape or there was rounding error

return lastElement;

Cory Foy
03/24/2009 05:00 PM by
Cory Foy

I think it's because you are combining the weighted distribution with the selection of the next page.

I don't know if this is any better, but maybe something like:

public class WeightedString

    {

        public string aString { get; set; }

        public int Weight { get; set; }


        public WeightedString(string s, int weight)

        {

            aString = s;

            Weight = weight;

        }

    }


    public class WeightedStrings : List

<string
{

        List

<weightedstring distributedStrings = new List <weightedstring (100);

        List

<weightedstring weightedStrings = new List <weightedstring ();

        public new void Add(WeightedString ws)

        {

            weightedStrings.Add(ws);

            foreach (WeightedString weightedString in weightedStrings)

            {

                for (int i = 0; i < weightedString.Weight; i++)

                {

                    distributedStrings.Add(weightedString);

                }

            }

        }


        public string GetNextString()

        {

            return distributedStrings[new Random().Next(0, 100)].aString;

        }

    }


    public class Weighted

    {

        public string GetNextString()

        {

            WeightedStrings strings = new WeightedStrings();

            strings.Add(new WeightedString("Hello", 80));

            strings.Add(new WeightedString("World", 20));

            return strings.GetNextString();

        }

    }
Yann Schwartz
03/24/2009 05:00 PM by
Yann Schwartz

(me again)

it's really useful for markov chains when you can have big probability differences between items, greater than 1%. Also, if you have a lot of items, you can implement a nice binary search to get to your value, but then you can kiss LINQ bye bye (because of its forward only streaming)

Cory Foy
03/24/2009 05:01 PM by
Cory Foy

Subtext stripped out all the generic statements. Let's try again:

public class WeightedString

    {

        public string aString { get; set; }

        public int Weight { get; set; }


        public WeightedString(string s, int weight)

        {

            aString = s;

            Weight = weight;

        }

    }


    public class WeightedStrings : List<string>

    {

        List<WeightedString> distributedStrings = new List<WeightedString>(100);

        List<WeightedString> weightedStrings = new List<WeightedString>();


        public new void Add(WeightedString ws)

        {

            weightedStrings.Add(ws);

            foreach (WeightedString weightedString in weightedStrings)

            {

                for (int i = 0; i < weightedString.Weight; i++)

                {

                    distributedStrings.Add(weightedString);

                }

            }

        }


        public string GetNextString()

        {

            return distributedStrings[new Random().Next(0, 100)].aString;

        }

    }


    public class Weighted

    {

        public string GetNextString()

        {

            WeightedStrings strings = new WeightedStrings();

            strings.Add(new WeightedString("Hello", 80));

            strings.Add(new WeightedString("World", 20));

            return strings.GetNextString();

        }

    }
Peter Morris
03/24/2009 05:03 PM by
Peter Morris

Aha! It was the RND that was the problem, it was returning the same value because it was being created each time. Making it static fixed it.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication45

{

class Program

{

    static void Main(string[] args)

    {

        var pages = new List

<page();

        pages.Add(new Page { PercentageToShow = 10 });

        pages.Add(new Page { PercentageToShow = 90 });


        for (int i = 0; i < 10; i++)

            Console.WriteLine(" = Page " + ChoosePage(pages).PercentageToShow.ToString());

        Console.ReadLine();


    }


    static Random RND = new Random();

    public static Page ChoosePage(List

<page pages)

    {

        int totalWeight = pages.Sum(p => p.PercentageToShow);

        int randomNumber = RND.Next(totalWeight);

        Console.Write("Chose RND " + randomNumber.ToString());

        return pages.SkipWhile(p => (randomNumber -= p.PercentageToShow) > 0).Take(1).Single();

    }

}


public class Page

{

    public int PercentageToShow { get; set; }

}

}

Cory Foy
03/24/2009 05:03 PM by
Cory Foy

Must...Test...First...

I meant to have the Add method clear the list before redistributing the elements to it. Sorry about that.

Peter Morris
03/24/2009 05:05 PM by
Peter Morris

Sorry, that would be better as...

    public static Page ChoosePage(List

<page pages)

    {

        int totalWeight = pages.Sum(p => p.PercentageToShow);

        int randomNumber = RND.Next(totalWeight);

        return pages.SkipWhile(p => (randomNumber -= p.PercentageToShow) > 0).First();

    }
Brian
03/24/2009 05:42 PM by
Brian

@Peter - Its probably a bit of a silly argument in this case, but the fact that it works for values that don't add to 100 is irrelevant. The spec specifically stated that they would sum to 100.

James Curran
03/24/2009 06:07 PM by
James Curran

The first question is "Why are you rebuilding the chance[] array every time?"

If the answer is "Because the PercentageToShow values may change between calls", then you are better off with some variant of the code offered by Adam/Matt/Peter. They are O(N) versus your O(100) (where N must be <100, or the algorithm won't work).

However, if the answer is "I'm not. It just looks that way in the snippet", then you probably better off with what you are doing. It's O(1) with a presumably amortizable O(100) one-time set-up.

Mathias
03/24/2009 07:59 PM by
Mathias

Matt's solution looks correct to me, and is the standard approach used in simulation. You can even optimize it a bit, by sorting your pages by decreasing probability: starting with the highest probability will likely terminate your loop earlier. Most likely irrelevant, given the size of the problem, though!

Avish
03/24/2009 09:40 PM by
Avish

Matt's solution is pretty much what I had in mind, so +1 there.

Peter Morris
03/25/2009 08:22 AM by
Peter Morris

Brian. Your original statement implied that my code was wrong because it doesn't assume the percentages add up to 100. My point is that it doesn't matter what the percentages add up to, my routine will work with the correct ratio anyway so there is no point in restricting it.

Besides, when a customer says "Always" what they actually mean is "Mostly", and when they say "Never" they mean "Hardly ever".

Comments have been closed on this topic.