1

那么在 C# 中创建一个循环的一个好的、简单的算法是什么,每次某个值出现在一个数组中时,它会将 1 加到另一个数组中的计数器上?

例如我有这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication22
{
    class Program
    {
        const int SIZE = 12;

        static void Main(string[] args)
        {
            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" };

            int[] Count = new int[4];
            int x = 0;
            int i = 0;

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

            for (i = 0; i < 4; i++)
            {
                Console.WriteLine("{0}", Count[4]);
            }
        }
    }
}

我只计算 4 个数字出现在 numbers 数组中的次数。有人建议我在第一个循环中使用该方法,但它似乎不起作用,并创建一个索引超出数组范围的错误。我想显示每个数字(5、7,9 和 1)出现在 4 行中的次数。

编辑:不使用 LINQ 或任何其他花哨的东西,如 Dictionary 或其他任何东西。

4

6 回答 6

7

由于本节,您会遇到索引越界错误:

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

请注意0,当只有.SIZE - 111Count4


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

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 个组,然后选择每个组中的第一个以留下ints 的集合。


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

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);
    }
}

对您的程序稍作修改,您可以获得一些结果。

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
于 2013-04-07T12:16:18.180 回答
4

用来LINQ做工作

using System.Linq;

var numQuery =
        from num in numbers
        where num == 5
        select num;

Console.WriteLine("Count of 5: " + numQuery.Count);

或使用method syntax

var numQuery = numbers.Where(num => num == 5);
Console.WriteLine("Count of 5: " + numQuery.Count);

有关概述,请参见此处,有关-syntax ,请参见此处。 找到一个样品,看这里query vs method
GroupBy

于 2013-04-07T12:12:13.577 回答
1

我使用正则表达式作为我的解决方案,因为我只有三个值。

String results = "" + one.ToString() + " " + two.ToString() + " " + three.ToString();
int count1 = Regex.Matches(results, @one.ToString()).Count;
int count2 = Regex.Matches(results, @two.ToString()).Count;
int count3 = Regex.Matches(results, @three.ToString()).Count;

似乎'hacky',但对我有用。它适用于字符串或数字,但前提是您使用一些值。在这种情况下非常有效。如果没有,我认为其他答案将是更好的选择。

于 2017-03-09T15:48:25.170 回答
0

您的计数数组有 4 个字段...

索引为 0、1、2 和 3 的一个

那么如果碰巧计算出像 4(或更大)这样的数字会发生什么?你的代码试图访问索引 4 ......它不存在......

于 2013-04-07T12:13:50.940 回答
0

这是寻找“计算一个值在数组中出现的次数”的简单解决方案想法:在数组解决方案中构建一个哈希映射:

using System.Collections.Generic;
using System.Text;

namespace GetArrEleFrequency
{
    class Program
    {
      static int[] Arr = new int[5] { 3, 3, 0, 2, 0 };
      static int[] Key = new int[5];
      static int[] value = new int[5];
      static void Main(string[] args)
      {
         int keyItr = -1, ValueItr = -1, tempIndex = 0, tempValue = 0;
         for (int i=0; i <= Arr.Length-1;i++) {
              if (!(isPresent(Arr[i]))) {
                   keyItr += 1;ValueItr += 1;
                   Key[keyItr] = Arr[i];
                   value[ValueItr] = 1;
             } else {
                   
                   value[tempIndex] = value[getIndex(Arr[i])] + 1;
            }
        }
        for (int i=0;i<=Key.Length-1;i++) {
              Console.WriteLine(Key[i] + "-" + value[i]);
        }
        Console.ReadKey();
     }
     public static Boolean  isPresent(int num) {
      Boolean temp = false;
      for (int i=0; i <= Key.Length-1;i++) {
        if (Key[i] == num) {
              temp = true;
              break;
        } else {
              temp = false;
        }
     }
     return temp;
   }
   public static int getIndex(int num) {
       int temp = 0;
       for (int i=0;i<=Key.Length-1;i++) {
             if (Key[i] == num) {
               break;
             } else {
             temp += 1;
       }
  }
  return temp;
   }
 }
}

Output :

    3 - 2
    0 - 2
    2 - 1
    0 - 0
    0 - 0
于 2021-01-13T15:51:15.513 回答
0
 static void Main(string[] args)
        {
            int[] arr = new int[] { 45, 34, 23, 67, 10, 99,99,10 };
            foreach(int i in arr.Distinct())
            {
                int count = occurance(arr,i);
                Console.WriteLine(i + "-Occurred For :" + count);
            }
            
            Console.ReadLine();
        }
        public static int occurance(int[] arr,int x)
        {
            int count = 0;
            foreach(int num in arr)
            {
                if(x==num)
                {
                    count++;
                }
            }
            return count;
        }
    }
于 2022-01-12T14:47:59.150 回答