478. Generate Random Point in a Circle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {

private final double radius;
private final double x_center;
private final double y_center;

public Solution(double radius, double x_center, double y_center) {
this.radius = radius;
this.x_center = x_center;
this.y_center = y_center;
}

public double[] randPoint() {
while (true) {
double randomX = ThreadLocalRandom.current().nextDouble(1.0000001) * 2 * radius - radius;
double randomY = ThreadLocalRandom.current().nextDouble(1.0000001) * 2 * radius - radius;
if (randomX * randomX + randomY * randomY <= radius * radius) {
return new double[]{x_center + randomX, y_center + randomY}; // 不要忘记根据圆心偏移
}
}
}

}

References

478. Generate Random Point in a Circle