PsyOps

WeighedRandom

Jan 23rd, 2013
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. public class WeighedRandom
  2. {
  3. private Random ran = new Random();
  4. private List<int[]> _Weight_Range = new List<int[]>();
  5. /// <summary>
  6. /// Add an array with 2 numbers
  7. /// [1] MaxValue for random number
  8. /// [2] Weight
  9. /// { maxval, weight }
  10. /// </summary>
  11. public List<int[]> Weight_Range
  12. {
  13. get { return _Weight_Range; }
  14. set { _Weight_Range = value; }
  15. }
  16.  
  17. private int[] WeightedNums = new int[] { };
  18. private int TotalNums = 0;
  19.  
  20. public void CreateRandomArray()
  21. {
  22. // use all the weights and total them to make the array total
  23. for (int t = 0; t < Weight_Range.Count; t++)
  24. TotalNums += Weight_Range[t][1];
  25.  
  26. // make the array
  27. WeightedNums = new int[TotalNums];
  28.  
  29. // Populate array with 0s
  30. for (int i = 0; i < TotalNums; i++)
  31. WeightedNums[i] = 0;
  32.  
  33. int count = 0;
  34.  
  35. for (int i = 0; i < Weight_Range.Count; i++)
  36. {
  37. for (int j = 0; j < Weight_Range[i][1]; j++)
  38. {
  39. WeightedNums[count++] = Weight_Range[i][0];
  40. }
  41. }
  42. }
  43.  
  44. public int ReturnRandomValue()
  45. {
  46. return ran.Next(1,WeightedNums[ran.Next(0,TotalNums)]);
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment