Skip to content

Commit

Permalink
More overloads for shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
YuriyDurov committed Jul 18, 2024
1 parent 72c99fe commit 9933baf
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/BitzArt.LinqExtensions/Extensions/ShuffleExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,33 @@ public static class ShuffleExtensions
/// Shuffles the elements of the collection
/// using <see href="https://en.wikipedia.org/wiki/Fisher-Yates_shuffle"/>
/// </summary>
/// <param name="source">The collection to shuffle.</param>
/// <param name="seed">The seed to use for the random number generator.</param>
/// <returns>A new IQueryable with the elements shuffled.</returns>
public static IQueryable<TSource> Shuffle<TSource>(this IQueryable<TSource> source)
=> source.Shuffle().AsQueryable();
public static IQueryable<TSource> Shuffle<TSource>(this IQueryable<TSource> source, int? seed = null)
=> source.Shuffle(seed).AsQueryable();

/// <summary>
/// Shuffles the elements of the collection
/// using <see href="https://en.wikipedia.org/wiki/Fisher-Yates_shuffle"/>
/// </summary>
/// <param name="source">The collection to shuffle.</param>
/// <param name="seed">The seed to use for the random number generator.</param>
/// <returns>A new collection with the elements shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, int? seed = null)
{
var random = seed.HasValue ? new Random(seed.Value) : _random;
return source.Shuffle(random);
}

/// <summary>
/// Shuffles the elements of the collection
/// using <see href="https://en.wikipedia.org/wiki/Fisher-Yates_shuffle"/>
/// </summary>
/// <param name="source">The collection to shuffle.</param>
/// <param name="random">The random number generator to use.</param>
/// <returns>A new collection with the elements shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{
// preserve the original collection
var list = new List<T>(source);
Expand All @@ -33,7 +50,7 @@ public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
while (n > 1)
{
n--;
var k = _random.Next(n + 1);
var k = random.Next(n + 1);
(list[n], list[k]) = (list[k], list[n]);
}
return list;
Expand Down

0 comments on commit 9933baf

Please sign in to comment.