Print 2-D co-ordinate points in ascending order followed by their frequencies in C++


In this problem, we are given 2 arrays x[] , y[] such that (x,y) gives a cordinate of a point in 2D plane. Our task is to print all points along with their frequencies of occurence.

Let’s take an example to understand the problem

Input: x[]={0, 1, 1, 0, 0} ; y[]={1, 2, 2, 2, 1}
Output
(0, 1) = 2
(1, 2) = 2
(0, 2) = 1

To solve this problem, we need to store frequency of occurence of each point. So this we need to use map data-structure. The key of the map is (x[i], y[i]), mapped value is integer frequency of occurence.

The program will show the implementation of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printFrequencyofPoint(int x[], int y[], int n){
   map<pair<int, int>, int> pFreq;
   for (int i = 0; i < n; i++)
   pFreq[make_pair(x[i], y[i])]++;
   map<pair<int, int>, int>::iterator i;
   for (i = pFreq.begin(); i != pFreq.end(); i++) {
      cout<<"("<<(i->first).first <<", "<< (i->first).second <<") -> ";
      cout<<i->second << "\n";
   }
}
int main() {
   int x[]={0, 1, 1, 0, 0};
   int y[]={1, 2, 2, 2, 1};
   int n=5;
   cout<<"The points and their frequency of occurance is :\n";
   printFrequencyofPoint(x, y, n);
   return 0;
}

Output

The points and their frequency of occurance is :
(0, 1) -> 2
(0, 2) -> 1
(1, 2) -> 2

Updated on: 03-Feb-2020

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements