Skip to content

Instantly share code, notes, and snippets.

@tupunco
Created April 25, 2016 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tupunco/4a425da52684d727262849078305e503 to your computer and use it in GitHub Desktop.
Save tupunco/4a425da52684d727262849078305e503 to your computer and use it in GitHub Desktop.
Weight Rand Helper
public interface IRng
{
int Next(int maxValue);
int Next(int minValue, int maxValue);
int Next();
void NextBytes(byte[] buffer);
double NextDouble();
}
public class WeightItem<T>
{
public T Value
{
get;
set;
}
public int Weight
{
get;
set;
}
}
public static class WeightRandHelper
{
public static T GetRandItemFromWeightList<T>(IList<WeightItem<T>> list, IRng rand)
{
if (list == null || list.Count == 0)
{
return default(T);
}
int num = 0;
int num2 = rand.Next(0, GetSum<T>(list));
foreach (var current in list)
{
num += current.Weight;
if (num > num2)
{
return current.Value;
}
}
return default(T);
}
private static int GetSum<T>(IList<WeightItem<T>> list)
{
if (list != null)
{
int sum = 0;
list.ForEach(x => sum += x.Weight);
return sum;
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment