Counting repeating numbers in an Array

前端 未结 5 1637
生来不讨喜
生来不讨喜 2020-12-22 02:53

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

相关标签:
5条回答
  • 2020-12-22 03:02
    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.

    0 讨论(0)
  • 2020-12-22 03:04

    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. =)

    0 讨论(0)
  • 2020-12-22 03:06

    You can use LINQ Distinct() extension method.

    http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx

    0 讨论(0)
  • 2020-12-22 03:20

    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.

    0 讨论(0)
  • 2020-12-22 03:24

    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.

    0 讨论(0)
提交回复
热议问题