Getting random numbers from a list of integers

前端 未结 7 903
慢半拍i
慢半拍i 2021-02-08 10:59

If I have a list of integers:

List myValues = new List(new int[] { 1, 2, 3, 4, 5, 6 } );

How would I get 3 random integer

7条回答
  •  攒了一身酷
    2021-02-08 11:05

    The simplest way would be something like this:

    var r = new Random();
    var myValues = new int[] { 1, 2, 3, 4, 5, 6 }; // Will work with array or list
    var randomValues = Enumerable.Range(0, 3)
        .Select(e => myValues[r.Next(myValues.Length)]);
    

    But a better method, if you want to ensure there are no duplicates is to use a shuffling algorithm, like the Fisher-Yates algorithm, then take the first 3 items:

    public static T[] Shuffle(IEnumerable items)
    {
        var result = items.ToArray();
        var r = new Random();
        for (int i = items.Length; i > 1; i--)
        {
            int j = r.Next(i);
            var t = result[j];
            result[j] = result[i - 1];
            result[i - 1] = t;
        }
    
        return result;
    }
    
    var myValues = new int[] { 1, 2, 3, 4, 5, 6 }; // Will work with any enumerable
    var randomValues = myValues.Shuffle().Take(3);
    

提交回复
热议问题