Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shuffle (rearrange randomly) a List<string> [duplicate]

Tags:

I need to rearrange my List array, it has a non-determinable number of elements in it.

Can somebody give me example of how i do this, thanks

like image 905
brux Avatar asked Mar 21 '11 20:03

brux


People also ask

Does random shuffle work on strings?

Because a string is an immutable type, and You can't modify the immutable objects in Python. The random. shuffle() doesn't' work with String.

How do you randomize the order of items in a list?

Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.

How do you randomly shuffle a string?

To shuffle strings or tuples, use random. sample() , which creates a new object. random. sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.

How do I randomly sort a list in Python?

To use shuffle, import the Python random package by adding the line import random near the top of your program. Then, if you have a list called x, you can call random. shuffle(x) to have the random shuffle function reorder the list in a randomized way. Note that the shuffle function replaces the existing list.


2 Answers

List<Foo> source = ... var rnd = new Random(); var result = source.OrderBy(item => rnd.Next()); 

Obviously if you want real randomness instead of pseudo-random number generator you could use RNGCryptoServiceProvider instead of Random.

like image 166
Darin Dimitrov Avatar answered Sep 29 '22 23:09

Darin Dimitrov


This is an extension method that will shuffle a List<T>:

    public static void Shuffle<T>(this IList<T> list) {         int n = list.Count;         Random rnd = new Random();         while (n > 1) {             int k = (rnd.Next(0, n) % n);             n--;             T value = list[k];             list[k] = list[n];             list[n] = value;         }     } 
like image 22
kprobst Avatar answered Sep 29 '22 22:09

kprobst