C# 在a到b之间获取n个不重复随机数

        //在min到max之间获取count个不重复随机值
        private List<int> getRandomNum(int min, int max,int count)
        {
            List<int> randoms = new List<int>();
            if (min > 0 && max >= min && count > 0)
            {
                if (max - min <= count)
                {
                    for (int i = min; i <= max; i++)
                        randoms.Add(i);
                }
                else
                {
                    int limitIdx = max - min;
                    List<int> arrs = Enumerable.Range(min, limitIdx + 1).ToList<int>();
                    for (int i = 0; i < count; i++)
                    {
                        int idx = GetNextRandomNum(0, limitIdx, true);
                        var tmp = arrs[idx];
                        randoms.Add(tmp);
                        arrs[idx] = arrs[limitIdx];
                        arrs[limitIdx] = tmp;
                        limitIdx--;
                    }
                }
            }
            return randoms;
        }

        //在min到max之间获取count个不重复随机值,并将不足的数量加到余量中        
        private List<int> getRandomNum(int min, int max, int count, ref int extraCount)
        {
            List<int> randoms = getRandomNum(min, max, count);
            extraCount += count - randoms.Count;
            return randoms;
        }

        static System.Random rdInt;        
        private int GetNextRandomNum(int min, int max, bool upBound = false)
        {
            if(rdInt == null)
            {
                rdInt = new System.Random((int)DateTime.Now.ToFileTimeUtc());
            }
            if(upBound)
            {
                max = max + 1;
            }
            int ret = rdInt.Next(min, max);
            return ret;
        }

猜你喜欢

转载自blog.csdn.net/aleefang/article/details/121269383