/
NLObP
/
AAEmu
Обзор
Документация
Войти
/
NLObP
/
AAEmu
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
develop
AAEmu.Commons/Utils/RandomElementByWeight.cs
28 строк
923 B
Roger Barreto
Performance + Refactoring + Code Style (#709)
16 сен 2023, 10:50
Не верифицирован
16 сен 2023, 10:50
0d89a74
Код
Авторство
О чём код?
using System; using System.Collections.Generic; using System.Linq; namespace AAEmu.Commons.Utils; public static class IEnumerableExtensions { public static T RandomElementByWeight<T>(this IEnumerable<T> sequence, Func<T, float> weightSelector) { float totalWeight = sequence.Sum(weightSelector); // The weight we are after... float itemWeightIndex = Rand.NextSingle() * totalWeight; float currentWeightIndex = 0.0f; foreach (var item in from weightedItem in sequence select new { Value = weightedItem, Weight = weightSelector(weightedItem) }) { currentWeightIndex += item.Weight; // If we've hit or passed the weight we are after for this item then it's the one we want.... if (currentWeightIndex >= itemWeightIndex) return item.Value; } return default; } }