-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathLINQShuffler.cs
More file actions
23 lines (22 loc) · 864 Bytes
/
LINQShuffler.cs
File metadata and controls
23 lines (22 loc) · 864 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
namespace Algorithms.Shufflers;
/// <summary>
/// LINQ Shuffle is a simple shuffling algorithm,
/// where the elements within a collection are shuffled using
/// LINQ queries and lambda expressions in C#.
/// </summary>
/// <typeparam name="T">Type array input.</typeparam>
public class LinqShuffler<T>
{
/// <summary>
/// First, it will generate a random value for each element.
/// Next, it will sort the elements based on these generated
/// random numbers using OrderBy.
/// </summary>
/// <param name="array">Array to shuffle.</param>
/// <param name="seed">Random generator seed. Used to repeat the shuffle.</param>
public T[] Shuffle(T[] array, int? seed = null)
{
var random = seed is null ? new Random() : new Random(seed.Value);
return array.OrderBy(x => random.Next()).ToArray();
}
}