How can i shuffle a list

Using

using System.Collections.Generic;

I made a list

private List<string> alpha = new List<string>{"A", "B", "C", "D"};

I need a new shuffled list

eg :- {“C”, “B”, “D”, “A”};

Using for loop i will show values in list.

How can i shuffle a list?

8 Answers

8

for (int i = 0; i < alpha.Count; i++) {
string temp = alpha*;*

  •   	int randomIndex = Random.Range(i, alpha.Count);*
    

_ alpha = alpha[randomIndex];_
* alpha[randomIndex] = temp;*
* }*

-1 This is the classic example of what not to do!! This will produce highly biased output. See here for more information.

Then what is the correct way to do!!?

@flamy Whoops, sorry, I should have mentioned that. You can fix the above code simply by changing line 3 to int randomIndex = Random.Range(i, alpha.Count);

I didnt find any difference between the code. then why do you add downvote

Well there is no difference, now that you've fixed the code ;) For those curious, the code used to say int randomIndex = Random.Range(0, alpha.Count); Which is incorrect for the reason listed above.

Try that :
listRand.Sort((a, b)=> 1 - 2 * Random.Range(0, 1));

It does not work. It shuffle but the result order is always the same. So, if the list is (A,B,C). The result of applying this function will always be (C,B,A).

this worked fine on me.

It's better if you do it like that: listRand.Sort((a, b)=> 1 - 2 * Random.Range(0, listRand.Count)); It works like this.

//================================================================//
//===================Fisher_Yates_CardDeck_Shuffle====================//
//================================================================//

	/// With the Fisher-Yates shuffle, first implemented on computers by Durstenfeld in 1964, 
	///   we randomly sort elements. This is an accurate, effective shuffling method for all array types.

	public static List<GameObject> Fisher_Yates_CardDeck_Shuffle (List<GameObject>aList) {

		System.Random _random = new System.Random ();

		GameObject myGO;

		int n = aList.Count;
		for (int i = 0; i < n; i++)
		{
			// NextDouble returns a random number between 0 and 1.
			// ... It is equivalent to Math.random() in Java.
			int r = i + (int)(_random.NextDouble() * (n - i));
			myGO = aList[r];
			aList[r] = aList*;*

_ aList = myGO;_
* }*

* return aList;*
* }*

Please be aware that this algorithm can produce index out of bounds exception, when "_random.NextDouble()" returns 1.0f. use this instead: int r = i + (int)(_random.NextDouble() * (n - i - 1));

this worked in my game & does a good job of shuffling my deck. Thanks very much, i used the regular .next but it did not work well.

I searched for an answer for this myself, and got so aggravated with all the different answers, that I made a clear concise way to do this myself:

public List<float> toShuffle = new List<float>();
    public List<float> shuffled = new List<float>();

    // ShuffleList(toShuffle);

    public void ShuffleList(List<float> list)
    {
        List<float> temp = new List<float>();
        temp.AddRange(list);

        for (int i = 0; i < list.Count; i++)
        {
            int index = Random.Range(0, temp.Count - 1);
            shuffled.Add(temp[index]);
            temp.RemoveAt(index);
        }
    }

I am sure this can be refined with more testing, and cooler heads. But this method works perfectly fine, and does exactly what I needed(to shuffle a List).

Amazing it works extremely well, ty.

public List shufflelist(List list)
{
LetterClass tempelement;
List templist = new List();
List listcopy = new List();
int rand;

    foreach (LetterClass item in list)
    {
        listcopy.Add(item);
    }

    while (listcopy.Count != 0)
    {
        rand = Random.Range(0, listcopy.Count);
        tempelement = listcopy[rand];
        templist.Add(listcopy[rand]);
        listcopy.Remove(tempelement);

    }

    return templist;

}

A quick google search yielded this: c# - Randomize a List<T> - Stack Overflow

I would suggest the Fisher-Yates shuffle as well. In fact, I would have if this answer wasn't here. :)

i cant use new Random() in unity 3d. i still confused how to implement Fisher-Yates in unity, Being a fresher.

Unity has its own random function. http://docs.unity3d.com/Documentation/ScriptReference/Random.Range.html

tried this. but repeatation comes

Dude, you wanted a random shuffle algorithm. We gave you several. If you wan't something specific, modify it to your needs. Don't expect people to give you something absolutely ready so you could just copy-paste it in. We're here to help, not do work for you.

after a little search this is how I got mine to work…
Maybe it helps somebody else :slight_smile:

void Shuffle(List<GameObject> a)
        {
            // Loop array
            for (int i = a.Count - 1; i > 0; i--)
            {
                // Randomize a number between 0 and i (so that the range decreases each time)
                int rnd = UnityEngine.Random.Range(0, i);
    
                // Save the value of the current i, otherwise it'll overwrite when we swap the values
                GameObject temp = a*;*

// Swap the new and old values
a = a[rnd];
a[rnd] = temp;
}

// Print
for (int i = 0; i < a.Count; i++)
{
Debug.Log(a*);*
}
}

Minor modernisation of the above. Note that I’ve placed this as a static function in its own class for easy access anywhere in the project, and that it uses Generics to accept an array of any kind. This is a shuffle-in-place version of the code, but could easily be adapted to return a new array.

public class Randomise
{
    public static void Shuffle<T>(ref T[] array) {
        for (int i = array.Length - 1; i > 0; i--) {
            var r = UnityEngine.Random.Range(0, i + 1);
            if (r == i) continue;
            var temp = array[i];
            array[i] = array[r];
            array[r] = temp;
        }
    }
}

Usage:
Randomise.Shuffle(ref myArray);