Best way to randomize an array with .NET

后端 未结 17 843
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 01:55

What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I\'d like to create a new Array with the same strings b

相关标签:
17条回答
  • 2020-11-22 02:41
    Random r = new Random();
    List<string> list = new List(originalArray);
    List<string> randomStrings = new List();
    
    while(list.Count > 0)
    {
    int i = r.Random(list.Count);
    randomStrings.Add(list[i]);
    list.RemoveAt(i);
    }
    
    0 讨论(0)
  • 2020-11-22 02:45

    This is a complete working Console solution based on the example provided in here:

    class Program
    {
        static string[] words1 = new string[] { "brown", "jumped", "the", "fox", "quick" };
    
        static void Main()
        {
            var result = Shuffle(words1);
            foreach (var i in result)
            {
                Console.Write(i + " ");
            }
            Console.ReadKey();
        }
    
       static string[] Shuffle(string[] wordArray) {
            Random random = new Random();
            for (int i = wordArray.Length - 1; i > 0; i--)
            {
                int swapIndex = random.Next(i + 1);
                string temp = wordArray[i];
                wordArray[i] = wordArray[swapIndex];
                wordArray[swapIndex] = temp;
            }
            return wordArray;
        }         
    }
    
    0 讨论(0)
  • 2020-11-22 02:45

    Here's a simple way using OLINQ:

    // Input array
    List<String> lst = new List<string>();
    for (int i = 0; i < 500; i += 1) lst.Add(i.ToString());
    
    // Output array
    List<String> lstRandom = new List<string>();
    
    // Randomize
    Random rnd = new Random();
    lstRandom.AddRange(from s in lst orderby rnd.Next(100) select s);
    
    0 讨论(0)
  • 2020-11-22 02:47

    This post has already been pretty well answered - use a Durstenfeld implementation of the Fisher-Yates shuffle for a fast and unbiased result. There have even been some implementations posted, though I note some are actually incorrect.

    I wrote a couple of posts a while back about implementing full and partial shuffles using this technique, and (this second link is where I'm hoping to add value) also a follow-up post about how to check whether your implementation is unbiased, which can be used to check any shuffle algorithm. You can see at the end of the second post the effect of a simple mistake in the random number selection can make.

    0 讨论(0)
  • 2020-11-22 02:48
    private ArrayList ShuffleArrayList(ArrayList source)
    {
        ArrayList sortedList = new ArrayList();
        Random generator = new Random();
    
        while (source.Count > 0)
        {
            int position = generator.Next(source.Count);
            sortedList.Add(source[position]);
            source.RemoveAt(position);
        }  
        return sortedList;
    }
    
    0 讨论(0)
提交回复
热议问题