Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly shuffle a List [duplicate]

Possible Duplicate:
Randomize a List<T> in C#
shuffle (rearrange randomly) a List<string>
Random plot algorithm

Hi I have the following list and I want to output the model into a list but do so randomly. I have seen a few examples but they seem to be really convuluted. I just want a simple way to do this?

List<Car> garage ----randomise------> List<string> models


List<Car> garage = new List<Car>();

garage.Add(new Car("Citroen", "AX"));
garage.Add(new Car("Peugeot", "205"));
garage.Add(new Car("Volkswagen", "Golf"));
garage.Add(new Car("BMW", "320"));
garage.Add(new Car("Mercedes", "CLK"));
garage.Add(new Car("Audi", "A4"));
garage.Add(new Car("Ford", "Fiesta"));
garage.Add(new Car("Mini", "Cooper"));
like image 731
Peter Crouch Avatar asked Aug 29 '12 14:08

Peter Crouch


People also ask

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 permute a list in Python?

The random. sample() function returns the random list with the sample size you passed to it. For example, sample(myList, 3) will return a list of 3 random items from a list. If we pass the sample size the same as the original list's size, it will return us the new shuffled list.

How do you shuffle multiple lists in Python?

Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator.


1 Answers

I think all you want is this, it's a simple way to do it;

Random rand = new Random();
var models = garage.OrderBy(c => rand.Next()).Select(c => c.Model).ToList();

//Model is assuming that's the name of your property

Note : Random(), ironically, isn't actually very random but fine for a quick simple solution. There are better algorithms out there to do this, here's one to look at;

http://en.wikipedia.org/wiki/Fisher-Yates_shuffle

like image 179
saj Avatar answered Oct 13 '22 00:10

saj