How could I improve this C# randomising method?

前端 未结 7 2173
南方客
南方客 2021-02-10 20:30

I think I\'ve settled on this as the most simple and unit-testable method for randomising a list, but would be interested to hear of any improvements.

public sta         


        
7条回答
  •  逝去的感伤
    2021-02-10 20:54

    I liked Dennis Palmers idea of returning a shuffled IEnumerable instead of shuffle the list in place, but using the RemoveAt method makes it slow. Here is an alternative without the RemoveAt method:

    public static IEnumerable Shuffle(IEnumerable list, int seed) {
      Random rnd = new Random(seed);
      List items = new List(list);
      for (int i = 0; i < items.Count; i++) {
        int pos = rnd.Next(i, items.Count);
        yield return items[pos];
        items[pos] = items[i];
      }
    }
    

    I thried this with 10000 integers, and it's about 30 times faster.

提交回复
热议问题