简体   繁体   中英

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#?

Output will be as below:

2 3 5 3 5

Number 1 : 0
Number 2 : 1
Number 3 : 2
Number 4 : 0
Number 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:

 // 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:

 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

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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