Skip to content

Instantly share code, notes, and snippets.

@stantoxt
Forked from mikedugan/fisher-yates.cs
Created June 25, 2024 09:14
Show Gist options
  • Save stantoxt/5a3ab8170dc176b631ead0e974707430 to your computer and use it in GitHub Desktop.
Save stantoxt/5a3ab8170dc176b631ead0e974707430 to your computer and use it in GitHub Desktop.
a simple C# implementation of the fisher-yates shuffle used to randomize array elements without bias
public static void Shuffle<T>(T[] array)
{
var random = _random;
for (int i = array.Length; i > 1; i--)
{
// Pick random element to swap.
int j = random.Next(i); // 0 <= j <= i-1
// Swap.
T tmp = array[j];
array[j] = array[i - 1];
array[i - 1] = tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment