How to count occurences of an int in an array?

后端 未结 5 1075
执念已碎
执念已碎 2021-01-07 15:57

My array is A = {2, 3, 4, 3, 4, 2, 4, 2, 4}

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

5条回答
  •  轮回少年
    2021-01-07 16:27

    This seems to be a homework or a tutorial. You have good solutions in Linq, but here is a simple version with basic algorithm:

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

提交回复
热议问题