简体   繁体   English

如何计算在C#中使用数组随机生成的每个数字

[英]How to count each number that is generated randomly using array in C#

How to count each number that gets generated randomly using array in C#?如何计算在 C# 中使用数组随机生成的每个数字?

Output will be as below:输出如下:

2 3 5 3 5 2 3 5 3 5

Number 1 : 0数字 1 : 0
Number 2 : 1数量 2 : 1
Number 3 : 2数字 3 : 2
Number 4 : 0数字 4 : 0
Number 5 : 2第 5 名:2

I did come out with random numbers but then I'm stuck to figure out how to count each number.我确实得出了随机数,但后来我一直想弄清楚如何计算每个数字。

int[] randNum;
randNum = new int[5];
Random randNum2 = new Random();

for (int i = 0; i < randNum.Length; i++)
{
    randNum[i] = randNum2.Next(0, 9);
    Console.Writeline(randNum[i]);
}

Console.WriteLine();

Usually, we use Dictionary for such problems:通常,我们使用Dictionary来解决这样的问题:

 // We build dictionary:
 Dictionary<int, int> counts = new Dictionary<int, int>();

 // 1000 random numbers  
 for (int i = 0; i < 1000; ++i) {
   int random = randNum2.Next(0, 9);

   if (counts.TryGetValue(random, out int count))
     counts[random] = count + 1;
   else 
     counts.Add(random, 1);    
 } 

 // Then query the dictionary, e.g. 
 // How many times 4 appeared?
 int result = counts.TryGetValue(4, out int value) ? value : 0; 
    

However, if numbers are of a small range (say, 0..8 , not -1000000..1000000000 ) we can use arrays:但是,如果数字范围很小(例如0..8 ,而不是-1000000..1000000000 ),我们可以使用数组:

 int numbersToGenerate = 5;
 int max = 9; 

 int[] counts = new int[max];

 for (int i = 0; i < numbersToGenerate; ++i) {
   int random = randNum2.Next(0, max);

   counts[random] += 1;     
 } 

 // Output:
 for (int i = 0; i < counts.Length; ++i)
   Console.WriteLine($"Number {i} : {counts[i]}");

If i understood you correctly you want an extra array with the counting output of the other array.如果我理解正确,您需要一个额外的数组,其中包含另一个数组的计数输出。

Then i think this is a simple solution:然后我认为这是一个简单的解决方案:

int[] arrResult = new int[9];

foreach(int number in randNum){
   if(arrResult[number] == null){
      arrResult[number] = 0;
   }
   arrResult[number] = arrResult[number] + 1;
}

if as i am reading in your code the numbers are from 0 to 8 so 9 numbers, this will output an Array where if the random numbers for example are 0 1 0 2 3 1 0如果我正在阅读你的代码,数字是从 0 到 8 所以是 9 个数字,这将输出一个数组,如果随机数例如是 0 1 0 2 3 1 0

 arrResult[0] == 3
 arrResult[1] == 2
 arrResult[3] == 1

there probably is a more efficent way with linq and different uses but this should be a solution which would work for your problem linq 和不同用途可能有更有效的方法,但这应该是一个可以解决您的问题的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM