Skip to content

Instantly share code, notes, and snippets.

@dimobelov
Forked from JerryBian/Fisher-Yates-C#.cs
Created April 13, 2020 13:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimobelov/2bb0abdf5ab9f63aa5dd87dbf00d4dbb to your computer and use it in GitHub Desktop.
Save dimobelov/2bb0abdf5ab9f63aa5dd87dbf00d4dbb to your computer and use it in GitHub Desktop.
Fisher-Yates-C#
public static class Program
{
private static readonly string[] Arrays = new[]
{
"jerry",
"Kate",
"Steve",
"Mark",
"Joe"
};
public static void Main(string[] args)
{
PrintArray(Arrays);
FisherYatesShuffle(Arrays);
PrintArray(Arrays);
Console.ReadKey();
}
private static void PrintArray<T>(IEnumerable<T> array)
{
var foo = string.Join(", ", array);
Console.WriteLine(foo);
}
private static void FisherYatesShuffle<T>(T[] array)
{
for (var i = array.Length - 1; i > -1; i--)
{
var j = new Random().Next(0, i);
Swap(ref array[i], ref array[j]);
}
}
private static void Swap<T>(ref T first, ref T second)
{
var temp = first;
first = second;
second = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment