Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle.
Implement the Solution class:
Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center).
randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y].
To generate a uniform random point inside a circle, we use polar coordinates. The angle is chosen uniformly from [0, 2π), and the radius is chosen so that points are uniformly distributed (using sqrt of a uniform random variable).
classSolution {
double rad, xc, yc;
publicSolution(double radius, double x_center, double y_center) {
rad = radius; xc = x_center; yc = y_center;
}
publicdouble[]randPoint() {
double theta = 2 * Math.PI* Math.random();
double r = rad * Math.sqrt(Math.random());
returnnewdouble[]{xc + r * Math.cos(theta), yc + r * Math.sin(theta)};
}
}
1
2
3
4
5
6
7
classSolution(val rad: Double, val xc: Double, val yc: Double) {
funrandPoint(): DoubleArray {
val theta = 2 * Math.PI * Math.random()
val r = rad * Math.sqrt(Math.random())
return doubleArrayOf(xc + r * Math.cos(theta), yc + r * Math.sin(theta))
}
}