﻿<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Ayende @ Rahien</title><link>http://ayende.com</link><description>Ayende @ Rahien</description><copyright>Copyright (C) Ayende Rahien  2004 - 2021 (c) 2026</copyright><ttl>60</ttl><item><title>Peter Morris commented on Challenge: probability based selection</title><description>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".
  
  
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment31</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment31</guid><pubDate>Wed, 25 Mar 2009 08:22:40 GMT</pubDate></item><item><title>Avish commented on Challenge: probability based selection</title><description>Matt's solution is pretty much what I had in mind, so +1 there.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment30</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment30</guid><pubDate>Tue, 24 Mar 2009 21:40:50 GMT</pubDate></item><item><title>Mathias commented on Challenge: probability based selection</title><description>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!
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment29</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment29</guid><pubDate>Tue, 24 Mar 2009 19:59:23 GMT</pubDate></item><item><title>James Curran commented on Challenge: probability based selection</title><description>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 &lt;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.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment28</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment28</guid><pubDate>Tue, 24 Mar 2009 18:07:28 GMT</pubDate></item><item><title>Brian commented on Challenge: probability based selection</title><description>@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.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment27</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment27</guid><pubDate>Tue, 24 Mar 2009 17:42:05 GMT</pubDate></item><item><title>Peter Morris commented on Challenge: probability based selection</title><description>Sorry, that would be better as...
  
  
		public static Page ChoosePage(List
&lt;page pages)
  
		{
  
			int totalWeight = pages.Sum(p =&gt; p.PercentageToShow);
  
			int randomNumber = RND.Next(totalWeight);
  
			return pages.SkipWhile(p =&gt; (randomNumber -= p.PercentageToShow) &gt; 0).First();
  
		}
  
&gt;</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment26</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment26</guid><pubDate>Tue, 24 Mar 2009 17:05:03 GMT</pubDate></item><item><title>Cory Foy commented on Challenge: probability based selection</title><description>Must...Test...First...
  
  
I meant to have the Add method clear the list before redistributing the elements to it. Sorry about that.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment25</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment25</guid><pubDate>Tue, 24 Mar 2009 17:03:10 GMT</pubDate></item><item><title>Peter Morris commented on Challenge: probability based selection</title><description>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
&lt;page();
  
			pages.Add(new Page { PercentageToShow = 10 });
  
			pages.Add(new Page { PercentageToShow = 90 });
  
  
			for (int i = 0; i &lt; 10; i++)
  
				Console.WriteLine(" = Page " + ChoosePage(pages).PercentageToShow.ToString());
  
			Console.ReadLine();
  
  
		}
  
  
		static Random RND = new Random();
  
		public static Page ChoosePage(List
&lt;page pages)
  
		{
  
			int totalWeight = pages.Sum(p =&gt; p.PercentageToShow);
  
			int randomNumber = RND.Next(totalWeight);
  
			Console.Write("Chose RND " + randomNumber.ToString());
  
			return pages.SkipWhile(p =&gt; (randomNumber -= p.PercentageToShow) &gt; 0).Take(1).Single();
  
		}
  
	}
  
  
	public class Page
  
	{
  
		public int PercentageToShow { get; set; }
  
	}
  
}
  
&gt;</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment24</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment24</guid><pubDate>Tue, 24 Mar 2009 17:03:01 GMT</pubDate></item><item><title>Cory Foy commented on Challenge: probability based selection</title><description>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&lt;string&gt;
  
	    {
  
	        List&lt;WeightedString&gt; distributedStrings = new List&lt;WeightedString&gt;(100);
  
	        List&lt;WeightedString&gt; weightedStrings = new List&lt;WeightedString&gt;();
  
  
	        public new void Add(WeightedString ws)
  
	        {
  
	            weightedStrings.Add(ws);
  
	            foreach (WeightedString weightedString in weightedStrings)
  
	            {
  
	                for (int i = 0; i &lt; 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();
  
	        }
  
	    }
  
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment23</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment23</guid><pubDate>Tue, 24 Mar 2009 17:01:44 GMT</pubDate></item><item><title>Yann Schwartz commented on Challenge: probability based selection</title><description>(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)
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment22</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment22</guid><pubDate>Tue, 24 Mar 2009 17:00:53 GMT</pubDate></item><item><title>Cory Foy commented on Challenge: probability based selection</title><description>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
&lt;string  
	    {
  
	        List
&lt;weightedstring	 distributedStrings = new List
&lt;weightedstring	(100);
  
	        List
&lt;weightedstring	 weightedStrings = new List
&lt;weightedstring	();
  
  
	        public new void Add(WeightedString ws)
  
	        {
  
	            weightedStrings.Add(ws);
  
	            foreach (WeightedString weightedString in weightedStrings)
  
	            {
  
	                for (int i = 0; i &lt; 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();
  
	        }
  
	    }
  
&gt;</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment21</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment21</guid><pubDate>Tue, 24 Mar 2009 17:00:06 GMT</pubDate></item><item><title>FallenGameR commented on Challenge: probability based selection</title><description>I have had a similar issue. There was a dictionary of elements (T) and there was a probability of choosing each element (double) [Dictionary
&lt;t,&gt;
 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 &lt;= 0.0 )
  
    {
  
        return lastElement;
  
    }
  
}
  
  
// We are at the end of the tape or there was rounding error
  
return lastElement;
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment20</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment20</guid><pubDate>Tue, 24 Mar 2009 16:56:14 GMT</pubDate></item><item><title>Yann Schwartz commented on Challenge: probability based selection</title><description>(continued)
  
  
read rnd instead of limit
  
  
int rnd = new Random().Next(0, 100);
  
pages.SkipWhile(p =&gt; p.PercentageToShow &lt; 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.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment19</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment19</guid><pubDate>Tue, 24 Mar 2009 16:51:02 GMT</pubDate></item><item><title>Peter Morris commented on Challenge: probability based selection</title><description>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.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment18</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment18</guid><pubDate>Tue, 24 Mar 2009 16:49:52 GMT</pubDate></item><item><title>Yann Schwartz commented on Challenge: probability based selection</title><description>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 =&gt; p.PercentageToShow &lt; 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)
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment17</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment17</guid><pubDate>Tue, 24 Mar 2009 16:48:33 GMT</pubDate></item><item><title>Brian commented on Challenge: probability based selection</title><description>@Peter - 10 + 20 != 100.
  
  
"We are assured that the numbers will always match to a 100."
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment16</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment16</guid><pubDate>Tue, 24 Mar 2009 16:40:20 GMT</pubDate></item><item><title>innesm commented on Challenge: probability based selection</title><description>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
  
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment15</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment15</guid><pubDate>Tue, 24 Mar 2009 16:39:38 GMT</pubDate></item><item><title>Peter Morris commented on Challenge: probability based selection</title><description>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.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment14</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment14</guid><pubDate>Tue, 24 Mar 2009 16:31:31 GMT</pubDate></item><item><title>innesm commented on Challenge: probability based selection</title><description>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.
  
  
  
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment13</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment13</guid><pubDate>Tue, 24 Mar 2009 16:25:44 GMT</pubDate></item><item><title>Remco Ros commented on Challenge: probability based selection</title><description>@Matt
  
  
that works too ! nice one.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment12</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment12</guid><pubDate>Tue, 24 Mar 2009 16:10:17 GMT</pubDate></item><item><title>Matt commented on Challenge: probability based selection</title><description>int rand = new Random().Next(0, 100);
  
int percentSoFar = 0;
  
foreach (var page in pages)
  
{
  
    percentSoFar += page.PercentageToShow;
  
    if (percentSoFar &gt;= rand) return page;
  
}
  
// error?
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment11</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment11</guid><pubDate>Tue, 24 Mar 2009 16:04:42 GMT</pubDate></item><item><title>Peter Morris commented on Challenge: probability based selection</title><description>Importantly
  
  
1: It's fast enough
  
2: It's very easy to understand
  
3: It works
  
  
So I wouldn't change it.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment10</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment10</guid><pubDate>Tue, 24 Mar 2009 15:56:09 GMT</pubDate></item><item><title>Remco Ros commented on Challenge: probability based selection</title><description>@Ayende
  
  
sorry, didn't test it.
  
  
This should work:
  
replace the last loop with:
  
  
			foreach (var kv in pagesperc)
  
			{
  
				if (number &lt;= kv.Value)
  
				{
  
					foundpage = kv.Key;
  
					break;
  
				}
  
			}
  
  
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment9</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment9</guid><pubDate>Tue, 24 Mar 2009 15:37:36 GMT</pubDate></item><item><title>Adam commented on Challenge: probability based selection</title><description>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 &lt; page.PercentageToShow) return page;
  
   index -= page.PercentageToShow;
  
}
  
  
?
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment8</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment8</guid><pubDate>Tue, 24 Mar 2009 15:34:17 GMT</pubDate></item><item><title>Brian commented on Challenge: probability based selection</title><description>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.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment7</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment7</guid><pubDate>Tue, 24 Mar 2009 15:32:03 GMT</pubDate></item><item><title>Ayende Rahien commented on Challenge: probability based selection</title><description>I don't understand how this is suppose to work.
  
Let us assume that you have 50% / 50%.
  
And random returns 7.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment6</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment6</guid><pubDate>Tue, 24 Mar 2009 15:20:35 GMT</pubDate></item><item><title>Brian commented on Challenge: probability based selection</title><description>@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?
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment5</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment5</guid><pubDate>Tue, 24 Mar 2009 15:19:23 GMT</pubDate></item><item><title>Remco Ros commented on Challenge: probability based selection</title><description>Sorry, comment messed up.
  
  
The dictionary should be generic {Page, int}
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment4</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment4</guid><pubDate>Tue, 24 Mar 2009 15:16:52 GMT</pubDate></item><item><title>Remco Ros commented on Challenge: probability based selection</title><description>how about:
  
  
var pagesperc = new Dictionary
&lt;page,&gt;
();
  
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
  
	}
  
}
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment3</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment3</guid><pubDate>Tue, 24 Mar 2009 15:15:49 GMT</pubDate></item><item><title>Brian commented on Challenge: probability based selection</title><description>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.
</description><link>http://ayende.com/3924/challenge-probability-based-selection#comment2</link><guid>http://ayende.com/3924/challenge-probability-based-selection#comment2</guid><pubDate>Tue, 24 Mar 2009 14:58:51 GMT</pubDate></item></channel></rss>