How to shuffle an array ?

Sofi0813

Member
Joined
Jul 25, 2021
Messages
7
Programming Experience
1-3
// I need help C# VS 2019. I am really new!!!
// I want to shuffle the array to get (for example; 0,3,2,1 or 1,3,0,2 etc...) and use the value on my labels, when I click on ButtonNext.
//How to shuffle an array? Lets say the updated array is array2: This means every time I click Next button I am getting four integers in different labels.
C#:
            int[] array = { 0, 1, 2, 3};  //List of 4 integers.
        
           
            private void ButtonNext_Click(object sender, EventArgs e) // my next button in Windows Form Application.
                {
                    lblAns1.Text = array2[0]; //This label should get the first position value from the shuffled-array
                    lblAns2.Text = array2[1]; //This label should get the second position value from the shuffled-array
                    lblAns3.Text = array2[2]; //This label should get the 3rd position value from the shuffled-array
                    lblAns4.Text = array2[3]; //This label should get the four position value from the shuffled-array
                }
 
Last edited by a moderator:

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
4,445
Location
Chesapeake, VA
Programming Experience
10+

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
4,250
Location
Sydney, Australia
Programming Experience
10+
This is the simplest option, as long as the level of randomness produced is sufficient for your purposes:
C#:
var rng = new Random();

var shuffledArray = originalArray.OrderBy(e => rng.NextDouble()).ToArray();
If you want to shuffle the existing array in place then you can do this:
C#:
var rng = new Random();
var keys = originalArray.Select(e => rng.NextDouble()).ToArray();

Array.Sort(keys, originalArray);
 
Top Bottom