From 48dfa8f1ee5e95132ed9b724f255317a8f761d2d Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Tue, 19 Jul 2022 15:20:19 +0200 Subject: [PATCH] Allow RandomExtensions to operate on any ICollection --- CHANGELOG.md | 1 + MLEM/Extensions/RandomExtensions.cs | 15 ++++++++------- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df1ba53..9495cec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ Improvements - Allow using multiple textures in a StaticSpriteBatch - Added GenericInput support for Buttons.None - Improved the way terminating formatting codes work by introducing SimpleEndCode +- Allow RandomExtensions to operate on any ICollection Removals - Marked AStar.InfiniteCost as obsolete diff --git a/MLEM/Extensions/RandomExtensions.cs b/MLEM/Extensions/RandomExtensions.cs index 59752aa..0741046 100644 --- a/MLEM/Extensions/RandomExtensions.cs +++ b/MLEM/Extensions/RandomExtensions.cs @@ -9,18 +9,19 @@ namespace MLEM.Extensions { public static class RandomExtensions { /// - /// Gets a random entry from the given list with uniform chance. + /// Gets a random entry from the given collection with uniform chance. /// /// The random /// The entries to choose from /// The entries' type /// A random entry - public static T GetRandomEntry(this Random random, IList entries) { - return entries[random.Next(entries.Count)]; + public static T GetRandomEntry(this Random random, ICollection entries) { + // ElementAt internally optimizes for IList access so we don't have to here + return entries.ElementAt(random.Next(entries.Count)); } /// - /// Returns a random entry from the given list based on the specified weight function. + /// Returns a random entry from the given collection based on the specified weight function. /// A higher weight for an entry increases its likeliness of being picked. /// /// The random @@ -29,7 +30,7 @@ namespace MLEM.Extensions { /// The entries' type /// A random entry, based on the entries' weight /// If the weight function returns different weights for the same entry - public static T GetRandomWeightedEntry(this Random random, IList entries, Func weightFunc) { + public static T GetRandomWeightedEntry(this Random random, ICollection entries, Func weightFunc) { var totalWeight = entries.Sum(weightFunc); var goalWeight = random.Next(totalWeight); var currWeight = 0; @@ -41,8 +42,8 @@ namespace MLEM.Extensions { throw new IndexOutOfRangeException(); } - /// - public static T GetRandomWeightedEntry(this Random random, IList entries, Func weightFunc) { + /// + public static T GetRandomWeightedEntry(this Random random, ICollection entries, Func weightFunc) { var totalWeight = entries.Sum(weightFunc); var goalWeight = random.NextDouble() * totalWeight; var currWeight = 0F;