Use a Dictionary<int,int>
, where the key is the random number and the value is the count:
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);
If you want to print the results for any numbers that are generated 0 times, you'll have to add some additional code to make sure a value of 0 is stored in the Dictionary for those values.
Something like this before the foreach
statement should work for you:
for (var i = 1; i < 11; i++)
if (!count.ContainsKey(i))
count.Add(i, 0);
An alternate solution, using a single-dimensional array, as suggested in the comments. A Dictionary
is pretty straight-forward, but this may be even easier to understand.
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]);