Skip to content

Commit

Permalink
Merge pull request #2 from AnnulusGames/add-removerandom
Browse files Browse the repository at this point in the history
Add: WeightedList<T>.RemoveRandom()
  • Loading branch information
AnnulusGames authored Aug 19, 2024
2 parents 0a125af + dc5c481 commit 3f3e39d
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/RandomExtensions/Collections/WeightedList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,25 @@ public void RemoveAt(int index)
totalWeight -= value.Weight;
}

public int RemoveRandom(IRandom random, out T item)
{
var r = random.NextDouble() * totalWeight;
var current = 0.0;

for (int i = 0; i < list.Count; i++)
{
current += list[i].Weight;
if (r <= current)
{
item = list[i].Value;
return i;
}
}

item = default!;
return -1;
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
Expand Down

0 comments on commit 3f3e39d

Please sign in to comment.