RageByte is coding an MMO (working title BR38) and I thought I would share our random weighted List code. Please dissect, interpret, and comment. It works great and please test (with your custom classes).
To use it would be:
WeightedList<int> lootTable = new WeightedList<int>();
lootTable.AddEntry(100, 8); // 80% chance to spawn item 100
lootTable.AddEntry(119, 2); // 20% chance to spawn item 119
int spawnedLoot = lootTable.GetRandom();
To use a custom class:
WeightedList<Monster> monsterList = new WeightedList<Monster>;
monsterList.AddEntry(monster1, 70); // 70% chance to spawn monster1
monsterList.AddEntry(monster2, 30); // 30% chance to spawn monster2
Monster monster = monsterList.GetRandom();
class WeightedList<T> {
private struct Entry {
public T Item;
public int Threshold;
}
private List<Entry> _entries = new List<Entry>();
private int _totalWeight;
public void AddEntry(T item, int weight) {
_totalWeight += weight;
_entries.Add(new Entry { Item = item, Threshold = _totalWeight });
}
private Random _rand = new Random();
public T GetRandom() {
int r = _rand.Next(1, _totalWeight + 1);
foreach (Entry entry in _entries) {
if (r <= entry.Threshold) return entry.Item;
}
return default;
}
}