From 82382e64eaebbc08774d20a2fee96b5c3517616b Mon Sep 17 00:00:00 2001 From: kesac Date: Tue, 4 Jun 2024 19:12:40 -0600 Subject: [PATCH] List extension methods no longer use an implicit static instance of Random --- Syllabore/Syllabore/ListExtensions.cs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/Syllabore/Syllabore/ListExtensions.cs b/Syllabore/Syllabore/ListExtensions.cs index 043ddae..7696709 100644 --- a/Syllabore/Syllabore/ListExtensions.cs +++ b/Syllabore/Syllabore/ListExtensions.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace Syllabore { @@ -11,7 +10,6 @@ namespace Syllabore /// public static class ListExtensions { - private static Random Random = new Random(); /// /// Clears the contents of the current list and replaces it @@ -39,9 +37,10 @@ public static int TotalWeight(this IList weightedItems) where T : IWeighte } /// - /// Returns a random item from an . + /// Returns a random item from an using the specified + /// instance of . /// - public static T RandomItem(this IList list) + public static T RandomItem(this IList list, Random random) { if(list.Count == 0) @@ -50,7 +49,7 @@ public static T RandomItem(this IList list) } else { - int selection = Random.Next(list.Count); + int selection = random.Next(list.Count); return list[selection]; } @@ -58,11 +57,12 @@ public static T RandomItem(this IList list) } /// - /// Returns a random item from an . + /// Returns a random item from an + /// using the specified instance of /// - public static T RandomItem(this ISet set) + public static T RandomItem(this ISet set, Random random) { - return set.ToList().RandomItem(); + return set.ToList().RandomItem(random); } /// @@ -70,11 +70,14 @@ public static T RandomItem(this ISet set) /// where T implements . /// Elements with a higher Weight value will have a higher probability /// of being selected over elements with lower Weight values. + /// + /// Random selection is done using the specified instance of . + /// /// - public static T RandomWeightedItem(this IList weightedItems) where T : IWeighted + public static T RandomWeightedItem(this IList weightedItems, Random random) where T : IWeighted { int totalWeight = weightedItems.TotalWeight(); - int randomSelection = Random.Next(totalWeight); + int randomSelection = random.Next(totalWeight); int runningTotal = 0;