Getting random numbers from a list of integers

前端 未结 7 894
慢半拍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:25

    One simple way:

    Random r = new Random();
    IEnumerable threeRandom = myValues.OrderBy(x => r.Next()).Take(3);
    

    The better way: Fisher–Yates shuffle:

    public static class EnumerableExtensions
    {
        public static IEnumerable Shuffle(this IEnumerable source)
        {
            return source.Shuffle(new Random());
        }
    
        public static IEnumerable Shuffle(this IEnumerable source, Random rng)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (rng == null) throw new ArgumentNullException("rng");
    
            return source.ShuffleIterator(rng);
        }
    
        private static IEnumerable ShuffleIterator(
            this IEnumerable source, Random rng)
        {
            List buffer = source.ToList();
            for (int i = 0; i < buffer.Count; i++)
            {
                int j = rng.Next(i, buffer.Count);
                yield return buffer[j];
    
                buffer[j] = buffer[i];
            }
        }
    }
    

    how you use it:

    IEnumerable threeRandom = myValues.Shuffle().Take(3);
    

提交回复
热议问题