Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 19 additions & 22 deletions src/GameUtils/Extensions/CollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -274,37 +274,34 @@ public static T WeightedRandom<T>(this IEnumerable<T> source, Func<T, float> wei
return list[count - 1];
}

var array = source.ToArray();
int arrayCount = array.Length;
if (arrayCount == 0)
{
throw new InvalidOperationException("Sequence contains no elements.");
}
T selected = default!;
float fallbackTotalWeight = 0f;
bool hasElements = false;

var arrayTotalWeight = 0f;
for (int i = 0; i < arrayCount; i++)
foreach (var item in source)
{
arrayTotalWeight += weightSelector(array[i]);
hasElements = true;
float weight = weightSelector(item);
if (weight <= 0f) continue;

fallbackTotalWeight += weight;

if (Random.Shared.NextDouble() * fallbackTotalWeight < weight)
{
selected = item;
}
}

if (arrayTotalWeight <= 0)
if (!hasElements)
{
throw new InvalidOperationException("Total weight must be greater than zero.");
throw new InvalidOperationException("Sequence contains no elements.");
}

var arrayTarget = (float)(Random.Shared.NextDouble() * arrayTotalWeight);
var arrayCumulative = 0f;

for (int i = 0; i < arrayCount; i++)
if (fallbackTotalWeight <= 0f)
{
var item = array[i];
arrayCumulative += weightSelector(item);
if (arrayTarget <= arrayCumulative)
{
return item;
}
throw new InvalidOperationException("Total weight must be greater than zero.");
}

return array[arrayCount - 1];
return selected;
}
}
Loading