Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class WeighedRandom
- {
- private Random ran = new Random();
- private List<int[]> _Weight_Range = new List<int[]>();
- /// <summary>
- /// Add an array with 2 numbers
- /// [1] MaxValue for random number
- /// [2] Weight
- /// { maxval, weight }
- /// </summary>
- public List<int[]> Weight_Range
- {
- get { return _Weight_Range; }
- set { _Weight_Range = value; }
- }
- private int[] WeightedNums = new int[] { };
- private int TotalNums = 0;
- public void CreateRandomArray()
- {
- // use all the weights and total them to make the array total
- for (int t = 0; t < Weight_Range.Count; t++)
- TotalNums += Weight_Range[t][1];
- // make the array
- WeightedNums = new int[TotalNums];
- // Populate array with 0s
- for (int i = 0; i < TotalNums; i++)
- WeightedNums[i] = 0;
- int count = 0;
- for (int i = 0; i < Weight_Range.Count; i++)
- {
- for (int j = 0; j < Weight_Range[i][1]; j++)
- {
- WeightedNums[count++] = Weight_Range[i][0];
- }
- }
- }
- public int ReturnRandomValue()
- {
- return ran.Next(1,WeightedNums[ran.Next(0,TotalNums)]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment