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
Generate Random Point in a Circle in C++
Suppose we have the radius and x-y positions of the center of a circle, we have to write a function called randPoint() which generates a uniform random point in the circle. So there will be some important points that we have to keep in mind −
- Input and output values are in floating-point.
- Radius and x-y position of the center of the circle is passed into the class constructor.
- A point on the circumference of the circle is considered to be in the circle.
- The randPoint() returns x-position and y-position of the random point, in that order.
So if the input is like [10, 5,-7.5], then it may generate some random points like [11.15792,-8.54781],[2.49851,-16.27854],[11.16325,-12.45479].
To solve this, we will follow these steps −
- Define a method called uniform(). This will work as follows −
- return random_number/MAX RANDOM
- Through the initializer initialize the rad, and center coordinate
- The randPoint will work as follows −
- theta = 2*Pi*uniform()
- r := square root of uniform()
- return a pair like (center_x + r*radius*cos(theta), center_y + r*radius*sin(theta))
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
const double PI = 3.14159265358979732384626433832795;
double m_radius, m_x_center, m_y_center;
double uniform() {
return (double)rand() / RAND_MAX;
}
Solution(double radius, double x_center, double y_center) {
srand(time(NULL));
m_radius = radius; m_x_center = x_center; m_y_center = y_center;
}
vector<double> randPoint() {
double theta = 2 * 3.14159265358979323846264 * uniform();
double r = sqrt(uniform());
return vector<double>{
m_x_center + r * m_radius * cos(theta),
m_y_center + r * m_radius * sin(theta)
};
}
};
main(){
Solution ob(10, 5, 7);
print_vector(ob.randPoint());
print_vector(ob.randPoint());
print_vector(ob.randPoint());
}
Input
Pass 10, 5, 7 into constructor Call randPoint() three times
Output
[1.5441, 9.14912, ] [-1.00029, 13.9072, ] [10.2384, 6.49618, ]
Advertisements