Created
April 25, 2016 14:00
-
-
Save tupunco/4a425da52684d727262849078305e503 to your computer and use it in GitHub Desktop.
Weight Rand Helper
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
public interface IRng | |
{ | |
int Next(int maxValue); | |
int Next(int minValue, int maxValue); | |
int Next(); | |
void NextBytes(byte[] buffer); | |
double NextDouble(); | |
} |
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
public class WeightItem<T> | |
{ | |
public T Value | |
{ | |
get; | |
set; | |
} | |
public int Weight | |
{ | |
get; | |
set; | |
} | |
} |
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
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