Simple way to randomly shuffle list
12,625
Try this (based on Fisher–Yates shuffle algorithm)
public static void ShuffleMe<T>(this IList<T> list)
{
Random random = new Random();
int n = list.Count;
for(int i= list.Count - 1; i > 1; i--)
{
int rnd = random.Next(i + 1);
T value = list[rnd];
list[rnd] = list[i];
list[i] = value;
}
}
List<Color> colors = new List<Color> ();
colors.Add(Color.Black);
colors.Add(Color.White);
colors.Add(Color.Red);
colors.ShuffleMe();
![Dan](https://i.stack.imgur.com/4JLvO.jpg?s=256&g=1)
Author by
Dan
Updated on June 04, 2022Comments
-
Dan about 2 years
I have a List of colors that I would like to be shuffled and mixed up at least a little.
I create a list using
List<Color> colors = new List<Color> (); colors.Add(Color.Black); colors.Add(Color.White); colors.Add(Color.Red);
But there is no
.Shuffle
I noticed a.Sort
but I don't think that's what I need. I searched for a while but all methods and other questions I found seem to be way over complicated for such a simple task, if there is a simpler way.I tried using
List<Color> colorList = new List<Color>(); public void SetupColors() { List<Color> colors = new List<Color> (); colors.Add(Color.BLACK); colors.Add(Color.WHITE); colors.Add(Color.RED); Random random = new Random(); int n = colors.Count; for (int i = colors.Count; i > 1; i--) { int rnd = random.Next(i + 1); var value = colors[rnd]; colors[rnd] = colors[i]; colors[i] = value; } colorList = colors; } public List<Message> getMessages() { List<Message> items = new List<Message> { new Message { . . . Background = colorList[0] }, new Message { . . . Background = colorList[1] } }; return items; }
but I keep getting IndexBound errors at
colorList[0]
andcolorList[1]
-
tigrou about 6 yearsLook at Fisher–Yates shuffle algorithm
-
Dan about 6 yearsI saw the 'duplicate' post but the answers are more complicated then they need to be, there has to be an easier way to shuffle the list
-
-
Dan about 6 yearsI edited my attempt into the question but I keep getting IndexBound errors
-
Gaurang Dave about 6 yearsEdit the for loop : for (int i = colors.Count - 1; i > 1; i--) . I updated answer as well. Mark as answer if it was useful and upvote.
-
Gaurang Dave about 6 yearsThere is no error while I am running it. I tested it. Where you are getting the errors? Also there is no need of doing this colorList = colors;
-
Dan about 6 yearsJust noticed I was running the getMessages before running SetupColors
-
Gaurang Dave about 6 years@Dan enjoy coding
-
Wesley over 3 years
int n
is unused. Is this intentional? @GaurangDave