This repository was archived by the owner on Jan 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomExtensions.cs
More file actions
51 lines (49 loc) · 1.32 KB
/
RandomExtensions.cs
File metadata and controls
51 lines (49 loc) · 1.32 KB
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
41
42
43
44
45
46
47
48
49
50
51
namespace RandomImageGenerator
{
/// <summary>
/// Extends Random class functionality.
/// Algorithm used:
/// <see href="https://en.wikipedia.org/wiki/Fisher-Yates_shuffle"/>
/// </summary>
internal static class RandomExtensions
{
/// <summary>
/// Shuffles selected array.
/// Use:
/// <code>
/// Random rng = new Random();
/// rng.ShuffleArray(myArray);
/// </code>
/// </summary>
public static void ShuffleArray<T>(this Random rng, T[] array)
{
int n = array.Length;
while (n > 1)
{
int k = rng.Next(n--);
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
/// <summary>
/// Shuffles selected list.
/// Use:
/// <code>
/// Random rng = new Random();
/// rng.ShuffleArray(myList);
/// </code>
/// </summary>
public static void ShuffleList<T>(this Random rng, List<T> list)
{
int n = list.Count;
while (n > 1)
{
int k = rng.Next(n--);
T temp = list[n];
list[n] = list[k];
list[k] = temp;
}
}
}
}