How could I improve this C# randomising method?

前端 未结 7 2205
南方客
南方客 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条回答
  •  Happy的楠姐
    2021-02-10 20:44

    You want a shuffle, and the best way to do that is the Fisher-Yates shuffle:

    public static IList Randomise(IList list, int seed) 
    {
        Random rng = new Random(seed); 
    
        List ret = new List(list);      
        int n = ret.Length;            
        while (n > 1) 
        {
            n--;                         
            int k = rng.Next(n + 1);  
            // Simple swap of variables
            T tmp = list[k];
            ret[k] = ret[n];
            ret[n] = tmp;
        }
        return ret;
    }
    

提交回复
热议问题