如何计算数组中int的出现次数?

时间:2015-03-06 07:33:39

标签: c#

我的数组是A = {2, 3, 4, 3, 4, 2, 4, 2, 4}

我需要一个数组B,它在索引i处存储数组A中i的出现次数。

我想要一个返回的代码:

b[2] = 3
b[3] = 2
b[4] = 4

请注意,如果上面的数组A中添加了任何数字,还应添加结果数组B

如果有人帮助我,我将非常感激。

下面给出了我迄今为止所做的代码。

    static void Main(string[] args)
    {
        int [] A = new int[4];
        int [] B = new int [A.Length];

        for (int i = 0; i > A.Length; i++)
        {
            B[A[i]] = B[i];
        }

    }

我是编程新手。我有这个场景写一个算法,我第一次写这种类型的算法。

5 个答案:

答案 0 :(得分:4)

如果您想了解 中每个项目的显示次数,例如数组, 你可以使用 Linq

  int[] a = new int[] 
   { 2, 3, 4, 3, 4, 2, 4, 2, 4 };

  // I'd rather not used array, as you suggested, but dictionary 
  Dictionary<int, int> b = a
    .GroupBy(item => item)
    .ToDictionary(item => item.Key, item => item.Count());

 ...

the outcome is

  b[2] == 3;
  b[3] == 2;
  b[4] == 4;

答案 1 :(得分:0)

使用Dictionary可以轻松完成您的任务。

以下是代码:

 Dictionary<int, int> ItemCount = new Dictionary<int, int>();

 int[] items = { 2, 3, 4, 3, 4, 2, 4, 2, 4 };

 foreach (int item in items)
 {
    if (ItemCount.ContainsKey(item))
    {
         ItemCount[item]++;
    }
    else {
        ItemCount.Add(item,1);
    }
 }

  Console.WriteLine("A|B");
  foreach (KeyValuePair<int,int> res in ItemCount)
  {
      Console.WriteLine(res.Key +"|"+res.Value);
  }

输出:

A  |   B
2  |   3
3  |   3
4  |   4

注意:我认为这对您来说可能过于先进,但这是一种简单的方法

没有字典,(原始方法)

     int[] A = { 2, 3, 4, 3, 4, 2, 4, 2, 4 };
     List<int> B = new List<int>(); // <= We need this to check already counted numbers in array

     int temp = 0; // <= A temporary variable to get a count per a specific elemet
     int count = 0; // < = Will hold number of elements we have already counted 

     Console.WriteLine("A|B");

     for (int i = 0; i < A.Length; i++)
     {
         temp = 0;

         // Check for a fresh number 
         if (!B.Contains(A[i]))
         {
             B.Add(A[i]);
             // For each element we try to count the number of occurrence 
             for (int j = 0; j < A.Length; j++)
             {
                 // Current element i matched with a element in array; counts increased 
                 if (A[i] == A[j])
                 {
                        temp++; // < = Local count
                        count++; // <= Kind of the global count of elements we have passed
                 }
             }

                Console.WriteLine(A[i] + "|" + temp); 
            }

           // We need to do this only for unique elements; when we have counted all elements in Array A we are done
           if (count >= A.Length)
           {
                break;
           }

      }

答案 2 :(得分:0)

这似乎是一个家庭作业或教程。你在Linq有很好的解决方案,但这是一个带有基本算法的简单版本:

static void Main(string[] args)
{
    int [] A = new int[4];
    // you should determine the size of B dynamically here...
    // Try to find yourself!
    int [] B = new int[999];

    /*  Code forgotten : initialize array B to 0s */

    for (int i = 0; i < A.Length; i++)
    {
        int item = A[i];
        // increase the number at index item
        B[item]++;
    }

}

答案 3 :(得分:0)

如果你正在寻找出现的次数,我已经做了一些例子,但是我还不确定你是说什么意思,如果你在A中添加数组它们应该出现在B中。要有这种功能你必须使用一些通知框架,不能有简单的数组。至少你应该将你想要添加元素的所有函数包装到A中,并进行计算,就像我在第三个例子中所示(带有结果数组E)。

            int[] a = new int[] { 2, 3, 4, 3, 4, 2, 4, 2, 4 };

        //version 1 - unsorted array
        //find top number of A array
        int max_number_a = a.Max() + 1;
        //initialize B,C of that size
        int[] b = new int[max_number_a];    //RESULT linq version
        int[] c = new int[max_number_a];    //RESULT double loop version
        for (int i = 0; i < max_number_a; i++)
        {
            //this is linq way
            b[i] = a.Where(x => x == i).Count();

            //this is double loop way
            c[i] = 0;           //initialize position so we can later count/increment when we find each instance of i inside A array
            for (int j = 0; j < a.Length; j++)
            {
                if (a[j] == i)   //check if a[j] is the number we are searching for
                    c[i]++;      //we have found one instance of J number, increase the B[i]
            }
        }

        //version 2 - sorted array
        int[] d = new int[max_number_a];    //RESULT sorted array
        //initialize all to zero
        for (int i = 0; i < max_number_a; i++) d[i] = 0;        //initialize array to zeros so we can count
        List<int> aList = a.OrderBy(x => x).ToList();            //this is linq ordering, choose any other way to order it
        while (aList.Count > 0)                                 // we have to use all a elements
        {
            d[aList[0]]++;
            aList.RemoveAt(0);
        }            

        //version 3 - the simple (right) way, and probably what you should be doing :)
        int[] e = new int[max_number_a];
        //initialize all to zero
        for (int i = 0; i < max_number_a; i++) e[i] = 0;        //initialize array to zeros so we can count
        for (int i = 0; i < a.Length; i++)
        {
            //we take e index of a[i] and increments its value
            e[a[i]]++;                             
            /*
             * int number_in_a = a[i];
             * int e_index_value = e[number_in_a];
             * e[number_in_a] = e_index_value + 1;
             */
        }

答案 4 :(得分:0)

查看此Fiddle

或者,如果您不想点击链接:

var a = new int[]{2, 3, 4, 3, 4, 2, 4, 2, 4};
var b = new int[a.Length];

    var aAsList = a.ToList();

    for (var i = 0;i < b.Length; i++)
    {
        var result = aAsList.Count(x=> x == i);
        b[i] = result;

        if (result != 0)
        {
            Console.WriteLine(string.Format("b[{0}] : {1}",i,result));
        }
    }