shuffle array in csharp

Here is one way to shuffle an array in C#:

main.cs
// Initialize array
int[] array = {1, 2, 3, 4, 5};

// Create random number generator
Random rng = new Random();

// Shuffle array
int n = array.Length;
while (n > 1)
{
    n--;
    int k = rng.Next(n + 1);
    int value = array[k];
    array[k] = array[n];
    array[n] = value;
}

// Display shuffled array
foreach (int element in array)
{
    Console.Write(element + " ");
}
378 chars
23 lines

In this code, we first initialize an array with some values. Then, we create a random number generator using the Random class. We use the Fisher-Yates shuffle algorithm to shuffle the array. Finally, we display the shuffled array using a foreach loop.

gistlibby LogSnag