Absolute distinct count in a sorted array?

CServer Side ProgrammingProgramming

In this section we will see how to count how many of elements whose absolute values are distinct? Suppose in an array there are few elements like {5, 5, 6, -5, 8, 2, -2, 1}, so there are 8 elements. But there are 5 elements {5, 6, 8, 2, 1} which are distinct. The -5 and 5 are not considered as different, they are same as their absolute value is same.

To solve this problem, we will use the Set data-structure. In set duplicate elements are not allowed. And when we are inserting item into the set, we will push only the absolute value.

Algorithm

absoluteDistinctCount(arr)

begin
   define set s;
   for each element e in arr, do
      insert |e| into s
   done
   return the number of elements of s
end

Example

 Live Demo

#include<iostream>
#include<set>
#include<cmath>
using namespace std;
int absoluteDistinctCount(int arr[], int n){
   set<int> s;
   for(int i = 0; i<n; i++){
      s.insert(abs(arr[i])); //insert the absolute value
   }
   return s.size();
}
main() {
   int arr[] = {5, 5, 6, -5, 8, 2, -2, 1};
   int n = (sizeof(arr))/(sizeof(arr[0]));
   cout << "Absolute Distinct Count: " << absoluteDistinctCount(arr, n);
}

Output

Absolute Distinct Count: 5
raja
Published on 26-Jul-2019 10:29:52
Advertisements