Terraria v1.4.4.9
Terraria source code documentation
Loading...
Searching...
No Matches
WeightedRandom.cs
Go to the documentation of this file.
1using System;
3using System.Linq;
4
5namespace Terraria.Utilities;
6
7public class WeightedRandom<T>
8{
10
11 public readonly UnifiedRandom random;
12
13 public bool needsRefresh = true;
14
15 private double _totalWeight;
16
18 {
19 random = new UnifiedRandom();
20 }
21
22 public WeightedRandom(int seed)
23 {
25 }
26
28 {
29 this.random = random;
30 }
31
37
43
45 {
46 this.random = random;
47 elements = theElements.ToList();
48 }
49
50 public void Add(T element, double weight = 1.0)
51 {
52 elements.Add(new Tuple<T, double>(element, weight));
53 needsRefresh = true;
54 }
55
56 public T Get()
57 {
58 if (needsRefresh)
59 {
61 }
62 double num = random.NextDouble();
63 num *= _totalWeight;
64 foreach (Tuple<T, double> element in elements)
65 {
66 if (num > element.Item2)
67 {
68 num -= element.Item2;
69 continue;
70 }
71 return element.Item1;
72 }
73 return default(T);
74 }
75
77 {
78 _totalWeight = 0.0;
79 foreach (Tuple<T, double> element in elements)
80 {
81 _totalWeight += element.Item2;
82 }
83 needsRefresh = false;
84 }
85
86 public void Clear()
87 {
89 }
90
92 {
93 return weightedRandom.Get();
94 }
95}
void Add(T element, double weight=1.0)
WeightedRandom(UnifiedRandom random, params Tuple< T, double >[] theElements)
readonly UnifiedRandom random
WeightedRandom(int seed, params Tuple< T, double >[] theElements)
WeightedRandom(params Tuple< T, double >[] theElements)
readonly List< Tuple< T, double > > elements
WeightedRandom(UnifiedRandom random)