Home > Software design >  How to use Random class to shuffle array in C#
How to use Random class to shuffle array in C#

Time:10-09

everyone. So I was trying to practice C# today, but I was stuck in figuring out how I can use the Random class to simply shuffle an array

like this for example:

using System;
                    
    public class Program
    {
        public static void Main()
        {
            int[] arr = {1,2,3,4,5};
        
            Random rand = new Random();
        
            for(int i =0; i < arr.Length; i  ){
                int shuffle = rand.Next(arr[i]);
                Console.WriteLine(arr[shuffle]);
            }
            
        }
    }

As you can see I tried to use this int shuffle = rand.Next(arr[i]); as a shuffler, but I guess it just duplicates some elements in the array.I'm still noob at this, thanks in advance for the response.

CodePudding user response:

The simplest way is get two random number (a, b, for example) each time. Then swap arr[a] and arr[b]. It's quality depends on how many times you swap element.

CodePudding user response:

There are a few solutions out there, but the one I had used it to create a random array and sort based on that

static class Program
{
    static void Main(string[] args)
    {
        var array = new[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

        Shuffle(ref array);

        foreach (var item in array)
        {
            Console.WriteLine(item);
        }
        // Fri
        // Wed
        // Sat
        // Thu
        // Mon
        // Sun
        // Tue

    }

    static readonly Random rng = new Random();

    public static void Shuffle<T>(ref T[] array)
    {
        double[] key = new double[array.Length];
        for (int i = 0; i < key.Length; i  )
        {
            key[i] = rng.NextDouble();
        }

        Array.Sort(key, array);
    }
}

CodePudding user response:

This type of shuffling is going to require seeding the Randomn class to the size of the array. And with each pass in the for loop, it's going to swap the current number with a random other number in the array.

Here is a sample of what the shuffle can look like:

int[] arr = {1,2,3,4,5};

Random rand = new Random();

for(int i = 0; i < arr.Length; i  ){
  int shuffle = rand.Next(arr.Length);
  int n = arr[i];
  arr.SetValue(arr[shuffle], i);
  arr.SetValue(n, shuffle);
}

Console.Write('['   arr[0].ToString());
for(int i = 1; i < arr.Length; i  ){
  Console.Write(","   arr[i]);
}
Console.Write("]");
  • Related