Last active
December 18, 2015 07:00
-
-
Save sapher/5743865 to your computer and use it in GitHub Desktop.
Selecting an item randomly from a collection according to related proportions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace Range | |
{ | |
public class ProportionValue<T> | |
{ | |
public double Proportion { get; set; } | |
public T Value { get; set; } | |
} | |
public static class ProportionValue | |
{ | |
public static ProportionValue<T> Create<T>(double proportion, T value) | |
{ | |
return new ProportionValue<T> { Proportion = proportion, Value = value }; | |
} | |
static readonly Random Random = new Random(); | |
public static T ChooseByRandom<T>( | |
this IEnumerable<ProportionValue<T>> collection) | |
{ | |
var rnd = Random.NextDouble(); | |
foreach (var item in collection) | |
{ | |
if (rnd < item.Proportion) | |
return item.Value; | |
rnd -= item.Proportion; | |
} | |
throw new InvalidOperationException( | |
"The proportions in the collection do not add up to 1."); | |
} | |
} | |
} | |
/*Exemple : | |
var vote= new[] { | |
ProportionValue.Create(true, 0.5); | |
ProportionValue.Create(false, 0.5); | |
} | |
var result = vote.ChooseByRandom();*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment