Find number of unique triangles among given N triangles in C++


In this problem, we are given three arrays s1[] , s2[] and s3[] of size N, denoting N triangles. Our task is to find the number of unique triangles among given N triangles.

For a triangle to be unique, all its side should be unique i.e. no other triangle should have the same sides.

Let’s take an example to understand the problem,

Input

s1[] = {1, 5, 3}
s2[] = {2, 3, 2}
s3[] = {4, 2, 5}

Output

1

Explanation

Triangle with sides 1 2 4 is unique.

Solution Approach

A simple solution to the problem is by counting the number of triangles which are unique.

For this, we will first sort each triangle’s side and then store in a map, if it’s values are unique increase the count.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countUniqueTriangle(int a[], int b[], int c[], int n) {
   vector<int> triSides[n];
   map<vector<int>, int> m;
   for (int i = 0; i < n; i++) {
      triSides[i].push_back(a[i]);
      triSides[i].push_back(b[i]);
      triSides[i].push_back(c[i]);
      sort(triSides[i].begin(), triSides[i].end());
      m[triSides[i]] = m[triSides[i]] + 1;
   }
   map<vector<int>, int>::iterator itr;
   int uniqueTriCount = 0;
   for (itr = m.begin(); itr != m.end(); itr++) {
      if (itr->second == 1)
         if (itr->second == 1)
            uniqueTriCount++;
   }
   return uniqueTriCount;
}
int main() {
   int s1[] = { 1, 5 ,3 };
   int s2[] = { 2, 3, 2 };
   int s3[] = { 4, 2, 5 };
   int N = sizeof(s1) / sizeof(s1);
   cout<<"The number of unique triangles is "<<countUniqueTriangle(s1, s2, s3, N);
   return 0;
}

Output

The number of unique triangles is 1

Updated on: 15-Mar-2021

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements