33 lines
919 B
C#
33 lines
919 B
C#
namespace OECS.PlayTest;
|
|
|
|
/// <summary>
|
|
/// A pool of agents selected by weight. Higher weight = more likely to be picked.
|
|
/// </summary>
|
|
public class WeightedAgentPool<TDecision>
|
|
{
|
|
private readonly List<(IAgent<TDecision> Agent, int Weight)> _agents = new();
|
|
private int _totalWeight;
|
|
private static readonly Random _rng = new();
|
|
|
|
public void Add(IAgent<TDecision> agent, int weight)
|
|
{
|
|
_agents.Add((agent, weight));
|
|
_totalWeight += weight;
|
|
}
|
|
|
|
public IAgent<TDecision> Pick()
|
|
{
|
|
if (_agents.Count == 0)
|
|
throw new InvalidOperationException("WeightedAgentPool is empty");
|
|
|
|
int roll = _rng.Next(_totalWeight);
|
|
int cumulative = 0;
|
|
foreach (var (agent, weight) in _agents)
|
|
{
|
|
cumulative += weight;
|
|
if (roll < cumulative)
|
|
return agent;
|
|
}
|
|
return _agents[^1].Agent;
|
|
}
|
|
} |