Skip to content
Merged
Show file tree
Hide file tree
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
Empty file added BenchmarkDotNet.config
Empty file.
31 changes: 15 additions & 16 deletions src/GameUtils/Extensions/CollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -236,38 +236,37 @@ public static T WeightedRandom<T>(this IEnumerable<T> source, Func<T, float> wei
return list[count - 1];
}

var itemsTotalWeight = 0f;
var hasElements = false;
foreach (var item in source)
var array = source.ToArray();
int arrayCount = array.Length;
if (arrayCount == 0)
{
hasElements = true;
itemsTotalWeight += weightSelector(item);
throw new InvalidOperationException("Sequence contains no elements.");
}

if (!hasElements)
var arrayTotalWeight = 0f;
for (int i = 0; i < arrayCount; i++)
{
throw new InvalidOperationException("Sequence contains no elements.");
arrayTotalWeight += weightSelector(array[i]);
}

if (itemsTotalWeight <= 0)
if (arrayTotalWeight <= 0)
{
throw new InvalidOperationException("Total weight must be greater than zero.");
}

var itemsTarget = (float)(Random.Shared.NextDouble() * itemsTotalWeight);
var itemsCumulative = 0f;
T lastItem = default!;
var arrayTarget = (float)(Random.Shared.NextDouble() * arrayTotalWeight);
var arrayCumulative = 0f;

foreach (var item in source)
for (int i = 0; i < arrayCount; i++)
{
lastItem = item;
itemsCumulative += weightSelector(item);
if (itemsTarget <= itemsCumulative)
var item = array[i];
arrayCumulative += weightSelector(item);
if (arrayTarget <= arrayCumulative)
{
return item;
}
}

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