+92 332 4229 857 99ProjectIdeas@Gmail.com

How to counting distinct elements in the array (C++ Tutorial)


Counting distinct elements in the array
CountDistinct() accepts 2 parameters; first is the array and second is the length of that array. And it displays distinct elements with the number of times each occurred.
Code of CountDistinct()

void CountDistinct( int arr[] , int len )
{
int count = 0;
int flag = 1;
      for ( int i = 0; i < len; i++ )
      {
            count = 0;
            flag = 1;
            for ( int j = 0; j < i; j++ )
            {
                  if ( arr[i] == arr[j] )
                        flag = flag + 1;
            }
                  if ( flag == 1 )
                  {
                        for (int k = 0; k < len ; k++ )
                        {
                              if ( arr[i] == arr[k] )
                                    count = count + 1;
                        }
                        cout << arr[i] << " - " << count <<endl;
                  }
      }
}

Summary of CountDistinct()
First for loop iterates from 0th  index to the size of the array..
There are 2 local variables count and flag, count keeps the track of number of occurrence of each distinct element in the array, and flag is used to keep track that the current element is distinct or not.
Second for loop checks that the current element of the array is distinct or not.
Thirst for loop counts the number of occurrence of each distinct element.

Example (C++)
#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

void CountDistinct( int arr[] , int len )
{
      for ( int i = 0; i < len; i++ )
      {
            int count = 0;
            int flag = 1;
            for ( int j = 0; j < i; j++ )
            {
                  if ( arr[i] == arr[j] )
                        flag = flag + 1;
            }
                  if ( flag == 1 )
                  {
                        for (int k = 0; k < len ; k++ )
                        {
                              if ( arr[i] == arr[k] )
                                    count = count + 1;
                        }
                        cout << arr[i] << " - " << count <<endl;
                  }
      }
}

int main()
{
      const int len = 10;
      int arr[len] = { 1 , 2 , 3 , 1 , 1 , 2 , 3 , 4 , 5 , 6 };
     
      CountDistinct( arr , len );

      _getche();
      return 0;
}

Output
1 - 3
2 - 2
3 - 2
4 - 1
5 - 1
6 – 1

0 comments: