Skip to content

Instantly share code, notes, and snippets.

@leyyce
Last active October 13, 2019 12:25
Show Gist options
  • Save leyyce/09c4f7b570c15034ce85eca969e94a2a to your computer and use it in GitHub Desktop.
Save leyyce/09c4f7b570c15034ce85eca969e94a2a to your computer and use it in GitHub Desktop.
C# Implementation of the Fischer-Yates shuffle
using System;
namespace Fisher_Yates_shuffle
{
class Program
{
static void Main(string[] args)
{
// Generate a set of numbers from user input...
Console.Write("Enter count of numbers to shuffle: ");
var count = Convert.ToInt32(Console.ReadLine());
var numbers = new int[count];
for (int i = 0; i < count; i++)
{
Console.Write($"Input the {i + 1}st number: ");
var num = Convert.ToInt32(Console.ReadLine());
numbers[i] = num;
}
Console.WriteLine("Original array: [" + string.Join("; ", numbers) + "]");
// Randomly swap numbers...
ShuffleIntArr(numbers);
Console.WriteLine("Swapped array: [" + string.Join("; ", numbers) + "]");
}
private static void ShuffleIntArr(int[] arr)
{
//Fisher Yates shuffle
Random rnd = new Random();
for (int i = arr.Length - 1; i >= 0; i--)
{
var randIndex = rnd.Next(0, i);
SwapAt(arr, i, randIndex);
}
}
private static void SwapAt(int[] arr, int a, int b)
{
var temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment