Fairly new to C#. Have an assignment for class that asks us to generate an array from user inputted values. This part is done and work's perfectly.
Now that the array is completed I need to be able to display each distinct number entered in the array in a Console.WriteLine, and how many times that number appeared and I'm a little lost on how to accomplish this.
Are you allow to use LINQ? If so, investigate GroupBy
and Count()
. Basically there's a one-liner which will work here, but as it's homework I'll let you work out the details for yourself... ask for more help when you've had a go though, if you run into problems.
You can create a dictionary in that the keys are numbers, and the values are counts of that specific number in the array, and then increase the values in the dictionary each time a number is found:
Example:
int[] arrayOfNumbers = new int[] { 1, 4, 2, 7, 2, 6, 4, 4, };
Dictionary<int, int> countOfItems = new Dictionary<int, int>();
foreach (int eachNumber in arrayOfNumbers)
{
if (countOfItems.ContainsKey(eachNumber))
countOfItems[eachNumber]++;
else
countOfItems[eachNumber] = 1;
}
This code works in all C# versions, but if you are using C# 3 or greater you could use LINQ, as others are suggesting. =)
You can use LINQ Distinct() extension method.
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
foreach (int item in array)
{
Console.Write(item.ToString() + " ");
int frequency = 0;
for (int i = 0; i < array.Length; ++i)
{
if (array[i] == item) ++frequency;
}
Console.WriteLine(frequency.ToString());
}
A dirty and brute force way. Considering your array is an "int" array. Otherwise, just change the types.
Without LINQ, you could keep track of the numbers you're generating. A data structure like a Dictionary
could work well, mapping the numbers to how many times you've seen them so far.