Skip to content

Instantly share code, notes, and snippets.

@sapher
Last active December 18, 2015 07:00
Show Gist options
  • Save sapher/5743865 to your computer and use it in GitHub Desktop.
Save sapher/5743865 to your computer and use it in GitHub Desktop.
Selecting an item randomly from a collection according to related proportions
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