簡體   English   中英

如何計算在C#中使用數組隨機生成的每個數字

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

如何計算在 C# 中使用數組隨機生成的每個數字?

輸出如下:

2 3 5 3 5

數字 1 : 0
數量 2 : 1
數字 3 : 2
數字 4 : 0
第 5 名:2

我確實得出了隨機數,但后來我一直想弄清楚如何計算每個數字。

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();

通常,我們使用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; 
    

但是,如果數字范圍很小(例如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]}");

如果我理解正確,您需要一個額外的數組,其中包含另一個數組的計數輸出。

然后我認為這是一個簡單的解決方案:

int[] arrResult = new int[9];

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

如果我正在閱讀你的代碼,數字是從 0 到 8 所以是 9 個數字,這將輸出一個數組,如果隨機數例如是 0 1 0 2 3 1 0

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

linq 和不同用途可能有更有效的方法,但這應該是一個可以解決您的問題的解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM