[LeetCode] Generate Random Point in a Circle

478. Generate Random Point in a Circle

Given the radius and x-y positions of the center of a circle, write a function randPoint which generates a uniform random point in the circle.

Note:

  • 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.
  • randPoint returns a size 2 array containing x-position and y-position of the random point, in that order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
private:
double r;
double x;
double y;
public:
Solution(double radius, double x_center, double y_center) : r(radius), x(x_center), y(y_center) {}

vector<double> randPoint() {
double theta = rand() * 1.0 / RAND_MAX * 2 * M_PI;
double hypotenuse = sqrt(rand() * 1.0 / RAND_MAX) * r;
return vector<double> {cos(theta) * hypotenuse + x, sin(theta) * hypotenuse + y};
}
};

/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(radius, x_center, y_center);
* vector<double> param_1 = obj->randPoint();
*/

Reference

균일 분포 관련 자료

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/17/PS/LeetCode/generate-random-point-in-a-circle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.