Best way to randomize an array with .NET

后端 未结 17 1121
隐瞒了意图╮
隐瞒了意图╮ 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:38

    This algorithm is simple but not efficient, O(N2). All the "order by" algorithms are typically O(N log N). It probably doesn't make a difference below hundreds of thousands of elements but it would for large lists.

    var stringlist = ... // add your values to stringlist
    
    var r = new Random();
    
    var res = new List(stringlist.Count);
    
    while (stringlist.Count >0)
    {
       var i = r.Next(stringlist.Count);
       res.Add(stringlist[i]);
       stringlist.RemoveAt(i);
    }
    

    The reason why it's O(N2) is subtle: List.RemoveAt() is a O(N) operation unless you remove in order from the end.

提交回复
热议问题