C#随机数生成器,具有单个数字的限制

Bha*_*dav -1 c# algorithm

我想random在1到100之间生成数字.1到100之间的任何数字都可以有3的最大限制.

例如,如果数字2生成3次,则它不应返回数字2,因为它已经生成3次.这里1到100之间的任何数字的最大限制是3,但任何数字都可以生成少于3次.

如何在不跟踪1到100之间的每个数字的情况下实现此目的?最大限制和数量范围可以更改.

编辑: 基于Zoran Horvat和Alexei Levenkov提供的答案,如果不跟踪数字而生成具有出现限制的随机数将很困难并且涉及复杂的解决方案.我厌倦了使用字典编写我自己的解决方案如下.

//for storing output
        List<int> output = new List<int>();
        //to keep track of numbers
        Dictionary<int, int> numberTrack = new Dictionary<int, int>();
        Random ran = new Random();
        //define max limit and range of numbers
        int maxLimit = 2, min = 1, max = 100 ;
        int no, count;
        //this for loop must run for any number less than max*maxLimit otherwise it will last for long time(may be forever). 
        for (int i = 0; i < max*maxLimit; i++)
        {
            //get random number.
            no = ran.Next(min, max+1);
            //check if random number exists in dictionary
            if (numberTrack.TryGetValue(no, out count))
            {
                //if exists than check for it occurrences 
                if (count >= maxLimit)
                {
                    //if occurrence is greater than maxLimit continue for next number.
                    i--;
                    continue;
                }
                else
                {
                    //else add number to output and update its occurrence count
                    numberTrack[no] += 1;
                    output.Add(no);
                }
            }
            else
            {
                //if random number does not exists in the dictionary than add it 
                //with occurrence of 1 and also add it to the ouptput.
                numberTrack.Add(no, 1);
                output.Add(no);
            }
        }
Run Code Online (Sandbox Code Playgroud)

但Sergey Berezovskiy和RenéVogt的解决方案完成了几行代码的任务.我非常感谢我从这个社区获得的所有帮助.

Ser*_*kiy 6

  1. 生成3*1..100个数字
  2. 洗他们
  3. 迭代洗牌收集

样品:

var random = new Random();
var maxRepetitionsCount = 3;
var numbers = Enumerable.Range(1,100)
       .SelectMany(i => Enumerable.Repeat(i, maxRepetitionsCount))
       .OrderBy(i => random.Next())
       .ToList();
Run Code Online (Sandbox Code Playgroud)

注意:没有选项可以跟踪事件计数而不跟踪事件计数.就像"我想做X而不做X"