• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
7
Question by sona.viswam · Jul 04, 2013 at 12:48 PM · c#monodeveloplistsshuffle

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?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

5 Replies

· Add your reply
  • Sort: 
avatar image
24
Best Answer

Answer by sona.viswam · Jul 05, 2013 at 06:32 AM

     for (int i = 0; i < alpha.Count; i++) {
         string temp = alpha[i];
         int randomIndex = Random.Range(i, alpha.Count);
         alpha[i] = alpha[randomIndex];
         alpha[randomIndex] = temp;
     }
Comment
Add comment · Show 17 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image BlueRaja_2014 · Jul 05, 2013 at 07:01 AM 4
Share
  • This is the classic example of what not to do!! This will produce highly biased output. See here for more information.

avatar image flamy · Jul 05, 2013 at 07:20 AM 2
Share

Then what is the correct way to do!!?

avatar image BlueRaja_2014 · Jul 05, 2013 at 09:46 AM 2
Share

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.

avatar image bawenang · May 30, 2017 at 07:06 AM 1
Share

@JVLVince The original is already correct since Random.Range with int is exclusive. $$anonymous$$eaning it will be randomed between i and alpha.Count -1.

avatar image JVLVince bawenang · Jul 25, 2017 at 03:54 PM 0
Share

tks, I got it. :) I will notice it.

avatar image bawenang · May 30, 2017 at 07:06 AM 1
Share

@JVLVince The original is already correct since Random.Range with int is exclusive. $$anonymous$$eaning it will be randomed between i and alpha.Count -1.

Show more comments
avatar image
5

Answer by mister kik · Jul 29, 2014 at 10:33 AM

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

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image chelder · Jun 15, 2016 at 12:55 PM 0
Share

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).

avatar image k3ndro · Jul 12, 2017 at 12:11 PM 0
Share

this worked fine on me.

avatar image LaterBuddy · Sep 02, 2021 at 01:21 AM 0
Share

It's better if you do it like that:

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

It works like this.

avatar image Bunny83 LaterBuddy · Sep 02, 2021 at 08:18 AM 0
Share

No, this makes no sense. The Sort method expects a delegate / function that returns either a positive, a negative or 0. When the value is 0 the two elements are considered equal. The other two cases sort them either the one way or the other. When you use "listRand.Count" as upper bounds it means only a random value of 0 could yield a positive number. Any other value would result in a negative number. So when you shuffle an array with many elements, most of the time you would return a negative value. The exact outcome now depends highly on the actual sorting algorithm. However I don't think the actual distribution of this approach is great or can actually be reasoned about. The basic "idea" behind this approach would be to randomly decide whether the two elements should be swapped or not. For this you would need to use

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

Passing 1 as second argument is pointless since in the case of the op (when using Random.Range(0, 1)) Random.Range would always return 0, all the time. The max bounds of the integer version of Random.Range is exclusive.


As I said the whole approach is pretty pointless. Sort also usually uses quick sort. Quick sort has an average and worst case runtime of O(n log n). In comparison when doing a normal fisher-yates shuffle the runtime is linear O(n).


So I highly recommend to stay away from this approach.

avatar image LaterBuddy Bunny83 · Sep 02, 2021 at 03:05 PM 0
Share

Thanks for advice. However, I did it and it seems efficient in that way I used before. It shuffles whole List -probably- in efficient way. But I'm not sure if we could use more efficient way. Do you have advice about it?

Some other guys used other ways like sorting them all with loops. So, I don't know how to measure efficiency... That would be nice if we can find a way better... Thanks again.

avatar image
4

Answer by pKallv · Apr 15, 2015 at 07:58 PM

     //================================================================//
     //===================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[i];
             aList[i] = myGO;
         }
 
         return aList;
     }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image KnightPista · Mar 27, 2017 at 10:24 AM 0
Share

Please be aware that this algorithm can produce index out of bounds exception, when "_random.NextDouble()" returns 1.0f.

use this ins$$anonymous$$d:

int r = i + (int)(_random.NextDouble() * (n - i - 1));

avatar image BlueRaja_2014 KnightPista · Mar 27, 2017 at 06:21 PM 0
Share

@$$anonymous$$nightPista: Random.NextDouble() never returns 1.0. See https://msdn.microsoft.com/en-us/library/system.random.nextdouble(v=vs.110).aspx

avatar image mar10 · Jan 19, 2019 at 09:45 PM 0
Share

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.

avatar image
0

Answer by Em3rgency · Jul 04, 2013 at 12:55 PM

A quick google search yielded this: http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp

Comment
Add comment · Show 9 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image iwaldrop · Jul 04, 2013 at 03:52 PM 1
Share

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

avatar image sona.viswam · Jul 05, 2013 at 06:00 AM 0
Share

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

avatar image mar10 sona.viswam · Jan 19, 2019 at 09:35 PM 0
Share

you have to use:

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

because unity has one & so does C# & the compiler gets confused as to which one to use.

avatar image Em3rgency · Jul 05, 2013 at 06:03 AM 0
Share

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

avatar image sona.viswam · Jul 05, 2013 at 06:12 AM 0
Share

tried this. but repeatation comes

avatar image mar10 sona.viswam · Jan 19, 2019 at 09:39 PM 0
Share

//here is an example... int a, v; List audClipIdxList; public AudioClip[] audClipArry;//supply in inspector void Awake(){ audClipIdxList=new List(audClipArry.Length); for(;a

avatar image Em3rgency · Jul 05, 2013 at 06:18 AM 0
Share

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.

Show more comments
avatar image
0

Answer by NatCou · Feb 09, 2019 at 05:21 PM

  after a little search this is how I got mine to work... 
  Maybe it helps somebody else :)  
 
 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[i];
     
                 // Swap the new and old values
                 a[i] = a[rnd];
                 a[rnd] = temp;
             }
     
             // Print
             for (int i = 0; i < a.Count; i++)
             {
                 Debug.Log(a[i]);
             }
         }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

36 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How do i use monodevelop 3.0.6 with unity 0 Answers

Scale fit? 1 Answer

Issues using the 'new' keyword 3 Answers

How to know which code depends on System.dll in mono C#? 1 Answer

My die function gets called without me asking it. 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges