vendredi 8 octobre 2021

How to use Random class to shuffle array in C#

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.




Aucun commentaire:

Enregistrer un commentaire