0%

LeetCode 478. Generate Random Point in a Circle

题目

原题在此

解析

线性的对半径取随机的话, 会导致origin附近的样本点比外围多, 使得样本分布不均匀, 要取sqrt().
延伸阅读

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
Solution(double radius, double x_center, double y_center): r{radius}, x{x_center}, y{y_center} {};
vector<double> randPoint() {
double theta = 2 * PI * ((double)rand() / RAND_MAX);
double ran = sqrt(((double)rand() / RAND_MAX));
double foo = x + ran * r * cos(theta), bar = y + ran * r * sin(theta);
return {foo, bar};
}

private:
double r, x, y;
const double PI = 3.14159265358979323846;
};



/**
* 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();
*/