且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算一个值在数组中出现的次数

更新时间:2022-04-11 08:24:08

由于此部分,您得到索引越界错误:

You're getting an index out of bounds error because of this section:

for (i = 0; i < SIZE - 1; i++)
{
    if (numbers[i] > 0 && numbers[i] < SIZE)
    {
        x = Count[i];

请注意,当 Count 仅具有4 的大小.

Notice that you're iterating through 0 to SIZE - 1 (11) when Count only has a size of 4.

不过,您可以使用 LINQ 轻松完成此任务.

You can do this task pretty easily with LINQ though.

int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };

var count = numbers
    .GroupBy(e => e)
    .Where(e => e.Count() == 4)
    .Select(e => e.First());

因此它按数字对数字进行分组,然后我们将列表细化为仅包含 4 组,然后选择每个组中的第一个以留下 int 的集合.

So it groups the numbers by their value, we then refine the list to only include groups of 4, then select the first of each to be left with a collection of ints.

这是一个非基于 LINQ 的解决方案,使用字典来存储数字计数.

Here is a non-LINQ based solution using a Dictionary to store the count of numbers.

int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
var dictionary = new Dictionary<int, int>();
var numbersWithFour = new List<int>();

foreach (var number in numbers)
{
    if (dictionary.ContainsKey(number))
        dictionary[number]++;
    else
        dictionary.Add(number, 1);
}

foreach (var val in dictionary)
{
    if (val.Value == 4)
    {
        numbersWithFour.Add(val.Key);
    }
}

对您的程序稍作修改即可获得一些结果.


With a little modification to your program you can get some results.

int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
string[] letters = new string[SIZE] { "m", "m", "s", "m", "s", "s", "s", "m", "s", "s", "s", "s" };
int[] values = new int[SIZE] { 15, 22, 67, 45, 12, 21, 24, 51, 90, 60, 50, 44 };
string[] status = new string[SIZE] { "f", "m", "f", "a", "m", "f", "f", "f", "m", "f", "m", "f" };

// Set the size of Count to maximum value in numbers + 1
int[] Count = new int[9 + 1];
int x = 0;
int i = 0;

for (i = 0; i < SIZE - 1; i++)
{
    if (numbers[i] > 0 && numbers[i] < SIZE)
    {
        // Use value from numbers as the index for Count and increment the count
        Count[numbers[i]]++;
    }
}

for (i = 0; i < Count.Length; i++)
{
    // Check all values in Count, printing the ones where the count is 4
    if (Count[i] == 4)
        Console.WriteLine("{0}", i);
}

输出:

7
9