-
-
Save dimobelov/2bb0abdf5ab9f63aa5dd87dbf00d4dbb to your computer and use it in GitHub Desktop.
Fisher-Yates-C#
This file contains hidden or 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
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