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
  • Save dimobelov/2bb0abdf5ab9f63aa5dd87dbf00d4dbb to your computer and use it in GitHub Desktop.
Save dimobelov/2bb0abdf5ab9f63aa5dd87dbf00d4dbb to your computer and use it in GitHub Desktop.

Revisions

  1. @JerryBian JerryBian renamed this gist Dec 18, 2018. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @JerryBian JerryBian renamed this gist Jan 23, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. @JerryBian JerryBian created this gist Jan 23, 2015.
    42 changes: 42 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    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;
    }
    }