-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathRandomizer.cs
40 lines (31 loc) · 1.59 KB
/
Randomizer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
namespace System.Collections.Generic
{
public static partial class Randomizer
{
public static IReadOnlyList<T> Randomize<T>(this IEnumerable<T> collection)
=> Randomize(collection, DefaultRandom.Default, DefaultCache<T>.Default);
public static IReadOnlyList<T> Randomize<T>(this IEnumerable<T> collection, IRandom rand)
=> Randomize(collection, rand, DefaultCache<T>.Default);
public static IReadOnlyList<T> Randomize<T>(this IEnumerable<T> collection, ICache<T> cache)
=> Randomize(collection, DefaultRandom.Default, cache);
public static IReadOnlyList<T> Randomize<T>(this IEnumerable<T> collection, IRandom rand, ICache<T> cache)
{
if (rand == null) throw new ArgumentNullException(nameof(rand));
if (cache == null) throw new ArgumentNullException(nameof(cache));
cache.Clear();
if (collection != null)
cache.Input.AddRange(collection);
while (cache.Input.Count > 0)
{
var index = rand.Range(0, cache.Input.Count);
cache.Output.Add(cache.Input[index]);
cache.Input.RemoveAt(index);
}
return cache.Output;
}
public static IReadOnlyList<T> RandomizeAllocated<T>(this IEnumerable<T> collection)
=> Randomize(collection, DefaultRandom.Default, new DefaultCache<T>());
public static IReadOnlyList<T> RandomizeAllocated<T>(this IEnumerable<T> collection, IRandom rand)
=> Randomize(collection, rand, new DefaultCache<T>());
}
}