如何计算一个数组中一个int的出现? [英] How to count occurences of an int in an array?

查看:69
本文介绍了如何计算一个数组中一个int的出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我需要一个数组B,该数组的索引号为 i ,该数字在数组A中出现 i 的次数.

I need an array B that stock at the index i the number of occurences of i in the array A.

我想要一个返回的代码:

I want a code which return:

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

请记住,如果在数组 A 中添加任何数字,也应在结果数组 B 中添加.

Keep in mind if any number adds in above array A should also add in resultant array B.

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

I will be very thankful if someone help me in this.

下面给出我到目前为止已完成的代码.

Below given my code which I have done so far.

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

    }

我是编程新手.我有这种情况来编写算法,而我是第一次编写这种类型的算法.

I am new to the programming. I got this scenario to write an algorithm and I am writing this type of algorithm first time.

推荐答案

如果您想了解每个项目在很多情况下如何出现在中,例如 array ,您可以使用 Linq :

If you want to find out how many time each item presents in the, say, array, you can use 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;

这篇关于如何计算一个数组中一个int的出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆