3

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] and colorList[1]

Dan
  • 1,100
  • 2
  • 13
  • 36
  • Look at Fisher–Yates shuffle algorithm – tigrou Mar 30 '18 at 07:25
  • I 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 Mar 30 '18 at 07:26

1 Answers1

10

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();
Gaurang Dave
  • 3,956
  • 2
  • 15
  • 34