How to count occurences of an int in an array?

后端 未结 5 855
天命终不由人
天命终不由人 2021-01-07 15:42

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:02

    Your task can be easily accomplished using a Dictionary.

    Here is the code :

     Dictionary ItemCount = new Dictionary();
    
     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 res in ItemCount)
      {
          Console.WriteLine(res.Key +"|"+res.Value);
      }
    

    output :

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

    Note : I think this might be too advance for you , but it's an easy way

    Without Dictionary, (A primitive approach)

         int[] A = { 2, 3, 4, 3, 4, 2, 4, 2, 4 };
         List B = new List(); // <= 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;
               }
    
          }
    

提交回复
热议问题