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 arr
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.
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
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.
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.