LeetCode 478. Generate Random Point in a Circle
This is the design problem.
we are given the radius and the xy position of the center of the curcle, we need to generates a uniform random point in the circle.
and we will be given a set of queries, like this:
Input:
[“Solution”,“randPoint”,“randPoint”,“randPoint”]
[[1,0,0],[],[],[]]
Output: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]
class Solution {
public Solution(double radius, double x_center, double y_center) {
}
public double[] randPoint() {
}
}
首先如何uniformly generate?
参见本博主此篇博文:
Java 如何取随机数?
本题也非常简单
遵从了一个原则:一个大的随机均匀取点的区域,其中的任何一个子区域也都是均匀的。
所以我们就先在正方形里面取 然后直到取到圆形中的。
通俗一点讲 这叫Rejection Sampling。
代码如下:
class Solution {
private double rad, dxc, dyc;
public Solution(double radius, double x_center, double y_center) {
rad = radius;
dxc = x_center;
dyc = y_center;
}
public double[] randPoint() {
//we should choose the number with in the sqaure range, and then check it if in the circle, we only return who is within the circle.
//we should choose the number in [dxc - rad, dxc + rad], and [dyx - rad, dyc - rad]
double x = Math.random() * 2 * rad - rad + dxc;
double y = Math.random() * 2 * rad - rad + dyc;
while (Math.sqrt(Math.pow(x - dxc, 2) + Math.pow(y - dyc, 2)) >= rad) {
x = Math.random() * 2 * rad - rad + dxc;
y = Math.random() * 2 * rad - rad + dyc;
}
return new double[]{x, y};
}
}

浙公网安备 33010602011771号