在C#中生成随机数的计数

时间:2015-03-06 02:17:34

标签: c#

我正在尝试创建一个列来计算生成的数量。以下是我想要的输出示例:

Number 1 has been generated 5 times.
Number 2 has been generated 2 times.
etc.

这是我目前的代码:

Random r = new Random();
        int plus = 0;
        for (int a = 0; a < 10; a++)
        {
            plus++;
            Console.Write("Week {0}: ", plus );
            for (int i = 0; i < 7; i++)
            {
                Console.Write(r.Next(1, 11));
                Console.Write(", ");
            }
            Console.WriteLine();
        }

3 个答案:

答案 0 :(得分:3)

使用Dictionary<int,int>,其中键是随机数,值是计数:

var count = new Dictionary<int, int>();

for (int i = 0; i < 7; i++)
{
    var rndValue = r.Next(1, 11);

    if (count.ContainsKey(rndValue))
        count[rndValue]++;
    else
        count.Add(rndValue, 1);

    Console.Write(rndValue);
    Console.Write(", ");
}

foreach (var c in count)
    Console.WriteLine("Number {0} has been generated {1} time(s).", c.Key, c.Value);

如果要打印0次生成的任何数字的结果,您必须添加一些额外的代码,以确保在字典中为这些值存储值0。

foreach语句之前的这样的内容对您有用:

for (var i = 1; i < 11; i++)
    if (!count.ContainsKey(i))
        count.Add(i, 0);

备注解决方案,使用一维数组,如评论中所示。 Dictionary很简单,但这可能更容易理解。

var count = new int[10];

for (int i = 0; i < 7; i++)
{
    var nextRnd = r.Next(1, 11);
    count[nextRnd - 1]++;

    Console.Write(nextRnd);
    Console.Write(", ");
}

for (var i = 0; i < count.Length; i++)
    Console.WriteLine("Number {0} has been generated {1} time(s).", i + 1, count[i]);

答案 1 :(得分:0)

var r = new Random();
var weeks = new List<List<int>>(
    Enumerable.Range(0, 10)
              .Select(w => new List<int>(Enumerable.Range(0, 7)
                                                   .Select(i => r.Next(1, 11)))));  

foreach (var week in weeks)
{
    Console.WriteLine("Week {0}: {1}", weeks.IndexOf(week), string.Join(",", week));
}

var allNumbers = weeks.SelectMany(n => n);
foreach (var number in allNumbers.Distinct().OrderBy(n => n))
{
    Console.WriteLine("{0} was generated {1} times", 
                      number,
                      allNumbers.Count(n => n == number));
}

答案 2 :(得分:0)

我想使用Dictionary来实现这个功能:

    Dictionary<int,int> rand_count_list = new Dictionary<int,int>();
    Random r = new Random();
    int plus = 0;
    for (int a = 0; a < 10; a++)
    {
        plus++;
        Console.Write("Week {0}: ", plus);
        for (int i = 0; i < 7; i++)
        {
            int rand = r.Next(1, 11);
            if (rand_count_list.ContainsKey(rand))
                rand_count_list[rand]++;
            else
                rand_count_list[rand] = 1;

            Console.Write(rand);
            Console.Write(", ");
        }
        Console.WriteLine();
    }

    foreach (int key in rand_count_list.Keys)
    {
        Console.Write("Number {0} has been generated {1} times. ", key, rand_count_list[key]);
    }