Skip to content

Commit

Permalink
List extension methods no longer use an implicit static instance of R…
Browse files Browse the repository at this point in the history
…andom
  • Loading branch information
kesac committed Jun 5, 2024
1 parent cfc160d commit 82382e6
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions Syllabore/Syllabore/ListExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Syllabore
{
Expand All @@ -11,7 +10,6 @@ namespace Syllabore
/// </summary>
public static class ListExtensions
{
private static Random Random = new Random();

/// <summary>
/// Clears the contents of the current list and replaces it
Expand Down Expand Up @@ -39,9 +37,10 @@ public static int TotalWeight<T>(this IList<T> weightedItems) where T : IWeighte
}

/// <summary>
/// Returns a random item from an <see cref="IList{T}"/>.
/// Returns a random item from an <see cref="IList{T}"/> using the specified
/// instance of <see cref="System.Random"/>.
/// </summary>
public static T RandomItem<T>(this IList<T> list)
public static T RandomItem<T>(this IList<T> list, Random random)
{

if(list.Count == 0)
Expand All @@ -50,31 +49,35 @@ public static T RandomItem<T>(this IList<T> list)
}
else
{
int selection = Random.Next(list.Count);
int selection = random.Next(list.Count);

return list[selection];
}

}

/// <summary>
/// Returns a random item from an <see cref="ISet{T}"/>.
/// Returns a random item from an <see cref="ISet{T}"/>
/// using the specified instance of <see cref="System.Random"/>
/// </summary>
public static T RandomItem<T>(this ISet<T> set)
public static T RandomItem<T>(this ISet<T> set, Random random)
{
return set.ToList<T>().RandomItem<T>();
return set.ToList<T>().RandomItem<T>(random);
}

/// <summary>
/// Returns a weighted-random item from an <see cref="IList{T}"/>,
/// where <c>T</c> implements <see cref="IWeighted"/>.
/// Elements with a higher <c>Weight</c> value will have a higher probability
/// of being selected over elements with lower <c>Weight</c> values.
/// <para>
/// Random selection is done using the specified instance of <see cref="System.Random"/>.
/// </para>
/// </summary>
public static T RandomWeightedItem<T>(this IList<T> weightedItems) where T : IWeighted
public static T RandomWeightedItem<T>(this IList<T> weightedItems, Random random) where T : IWeighted
{
int totalWeight = weightedItems.TotalWeight();
int randomSelection = Random.Next(totalWeight);
int randomSelection = random.Next(totalWeight);

int runningTotal = 0;

Expand Down

0 comments on commit 82382e6

Please sign in to comment.