0478. Generate Random Point in a Circle (M)
Generate Random Point in a Circle (M)
题目
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.
Example 1:
Input:
["Solution","randPoint","randPoint","randPoint"]
[[1,0,0],[],[],[]]
Output: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]
Example 2:
Input:
["Solution","randPoint","randPoint","randPoint"]
[[10,5,-7.5],[],[],[]]
Output: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution
's constructor has three arguments, the radius, x-position of the center, and y-position of the center of the circle. randPoint
has no arguments. Arguments are always wrapped with a list, even if there aren't any.
题意
在圆内随机生成一个点。
思路
极坐标容易处理:生成一个随机的角度rad,一个随机的长度len,len在0-radius之间,那么得到的随机点就是(len*cos(rad) + x, len*sin(rad) + y)。问题在于如果len直接由radius乘一个0-1的随机数random生成,最后得到的结果并不是对于面积等概率的。举个例子,如果要在半径为R的圆中取一点,使该点正好在半径为R/2的同心圆中,概率为1/4而不是1/2。因此应当先对random去平方根,再与半径相乘来得到len值。
代码实现
Java
class Solution {
private double r, x, y;
private Random random;
public Solution(double radius, double x_center, double y_center) {
r = radius;
x = x_center;
y = y_center;
random = new Random();
}
public double[] randPoint() {
double len = Math.sqrt(random.nextDouble()) * r;
double rad = random.nextDouble() * Math.PI * 2;
return new double[]{len * Math.cos(rad) + x, len * Math.sin(rad) + y};
}
}