OneBite.Dev - Coding blog in a bite size

Shuffle The Elements In An Array In C#

Code snippet for how to Shuffle The Elements In An Array In C# with sample and detail explanation

Manipulating arrays is common in C# or in any programming language. Shuffling the elements in an array is one of the prominent tasks usually performed for a wide array of applications such as gaming, statistics, machine learning and more. In this article, we will be demonstrating a simple way of doing this in C#.

Code snippet for Array Shuffling

Here’s a simple C# code snippet implementing the Fisher-Yates algorithm - a popular and efficient algorithm for shuffling elements in an array:

using System;

public class Program
{
    public static void Main()
    {
        int[] array = { 1, 2, 3, 4, 5 };
        Random rand = new Random();

        for (int i = array.Length - 1; i > 0; i--)
        {
            int j = rand.Next(i + 1);
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }

        foreach (var item in array)
        {
            Console.Write(item + " ");
        }
    }
}

Code Explanation for Array Shuffling

Let’s break down the code snippet and understand how it works, step-by-step:

  1. First, we create an integer array array with some initial values [1, 2, 3, 4, 5].

  2. Then, we create an instance of the Random class, named rand.

  3. We start a loop from the end of the array towards its beginning (for (int i = array.Length - 1; i > 0; i--)). This technique is vital for the Fisher-Yates algorithm.

  4. Inside the loop, we generate a random integer j which ranges from 0 to the current i.

  5. Then we swap the numbers at the ith and jth index of the array. To swap, we first keep the ith value in a temporary variable temp, then replace the ith value with the jth value and finally put the temp value at the jth index.

  6. After the loop finishes, we have a shuffled version of our original array.

  7. Finally, we print out the values of the shuffled array to the console using a foreach loop.

Thus, with this simple implementation of the Fisher-Yates algorithm, you can easily shuffle the elements in an array in C#. It’s worth noting that while the Fisher-Yates algorithm guarantees an unbiased random distribution, the quality will ultimately be determined by the underlying random number generator, in this case, the Random class. For a cryptographically secure random number generator, consider using RNGCryptoServiceProvider.

c-sharp