Created
March 20, 2021 16:41
-
-
Save RamonBeast/dc03fcd8327df4e56d74911ca6f8ad72 to your computer and use it in GitHub Desktop.
C# class to shuffle an array using Fisher-Yates algorithm in order to guarantee a non-repeating list of random integers within a given range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
/* | |
C# implementation of Fisher-Yates shuffling with automatic reshuffling. | |
This class can be used to generate a series of numbers from 0 to ``numElements`` that is guaranteed | |
not to repeat. The array is automatically reshuffled when all elements have been picked. | |
*/ | |
public class FisherYatesShuffling | |
{ | |
Random rnd = new Random(); | |
int[] elements { get; } | |
int idx { get; set; } = 0; | |
public FisherYatesShuffling(int numElements) { | |
if (numElements > 0) { | |
elements = new int[numElements]; | |
} else { | |
throw new ArgumentException("numElements must be greater than 0"); | |
} | |
for (int i = 0; i < numElements; i++) { | |
elements[i] = i; | |
} | |
shuffle(); | |
} | |
public void shuffle() { | |
for (int i = elements.Length - 1; i > 0; i--) { | |
int j = rnd.Next(0, i); | |
int t = elements[j]; | |
elements[j] = elements[i]; | |
elements[i] = t; | |
} | |
idx = 0; | |
} | |
public int getNumber() { | |
if (idx >= elements.Length) { | |
shuffle(); | |
} | |
int n = elements[idx++]; | |
return n; | |
} | |
} | |
// Usage example | |
class TestShuffle { | |
static public void Main(String[] args) { | |
int elements = 10; | |
FisherYatesShuffling fys = new FisherYatesShuffling(elements); | |
// Outputs 2 * "elements" in order to force a reshuffling | |
for (int i = 0; i < elements * 2; i++) { | |
Console.WriteLine(fys.getNumber()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment