
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Angular Sweep Algorithm in C++
The algorithm to find the maximum number of points that can be enclosed in a circle of a given radius. This means that for a circle of radius r and a given set of 2-D points, we need to find the maximum number of points that are enclosed (lying inside the circle not on its edges) by the circle.
For, this is the most effective method is the angular sweep algorithm.
Algorithm
There are nC2 points given in the problem, we need to find the distance between each of these points.
Take an arbitrary point and get the maximum number of points lying in the circle when rotated about the point P.
Returning the maximum number of points that can be enclosed as the final return value of the problem.
Example
#include <bits/stdc++.h> using namespace std; #define MAX_POINTS 500 typedef complex<double> Point; Point arr[MAX_POINTS]; double dis[MAX_POINTS][MAX_POINTS]; int getPointsInside(int i, double r, int n) { vector <pair<double, bool> > angles; for (int j = 0; j < n; j++) { if (i != j && dis[i][j] <= 2*r) { double B = acos(dis[i][j]/(2*r)); double A = arg(arr[j]-arr[i]); double alpha = A-B; double beta = A+B; angles.push_back(make_pair(alpha, true)); angles.push_back(make_pair(beta, false)); } } sort(angles.begin(), angles.end()); int count = 1, res = 1; vector <pair<double, bool>>::iterator it; for (it=angles.begin(); it!=angles.end(); ++it) { if ((*it).second) count++; else count--; if (count > res) res = count; } return res; } int maxPoints(Point arr[], int n, int r) { for (int i = 0; i < n-1; i++) for (int j=i+1; j < n; j++) dis[i][j] = dis[j][i] = abs(arr[i]-arr[j]); int ans = 0; for (int i = 0; i < n; i++) ans = max(ans, getPointsInside(i, r, n)); return ans; } int main() { Point arr[] = {Point(6.47634, 7.69628), Point(5.16828, 4.79915), Point(6.69533, 6.20378)}; int r = 1; int n = sizeof(arr)/sizeof(arr[0]); cout << "The maximum number of points are: " << maxPoints(arr, n, r); return 0; }
Output
The maximum number of points are: 2
Advertisements