Generate Random Point in a Circle
Problem
Implement a class that, given radius and center, returns a uniformly random point in the circle.
radius = 1.0, x_center = 0, y_center = 0"(0.0123, -0.4567)"import math, random
class Solution:
def __init__(self, radius, x_center, y_center):
self.r = radius; self.x = x_center; self.y = y_center
def randPoint(self):
r = self.r * math.sqrt(random.random())
theta = 2 * math.pi * random.random()
return [self.x + r * math.cos(theta), self.y + r * math.sin(theta)]
class Solution {
constructor(radius, xCenter, yCenter) {
this.R = radius; this.X = xCenter; this.Y = yCenter;
}
randPoint() {
const r = this.R * Math.sqrt(Math.random());
const theta = 2 * Math.PI * Math.random();
return [this.X + r * Math.cos(theta), this.Y + r * Math.sin(theta)];
}
}
class Solution {
double r, x, y;
Random rnd = new Random();
public Solution(double radius, double x_center, double y_center) {
r = radius; x = x_center; y = y_center;
}
public double[] randPoint() {
double rr = r * Math.sqrt(rnd.nextDouble());
double t = 2 * Math.PI * rnd.nextDouble();
return new double[]{ x + rr * Math.cos(t), y + rr * Math.sin(t) };
}
}
class Solution {
double r, x, y;
public:
Solution(double radius, double x_center, double y_center) : r(radius), x(x_center), y(y_center) {}
vector randPoint() {
double rr = r * sqrt((double) rand() / RAND_MAX);
double t = 2 * M_PI * ((double) rand() / RAND_MAX);
return { x + rr * cos(t), y + rr * sin(t) };
}
};
Explanation
To pick a point inside a circle we use polar coordinates: choose an angle and a distance from the center. The tricky part is making the points spread out evenly across the whole area, not bunched up in the middle.
The angle is easy: pick theta uniformly between 0 and 2π. The distance needs care. If we picked the radius uniformly, points would cluster near the center because the inner ring has far less area than the outer ring.
The fix is to scale the radius by a square root: r = R * sqrt(U) where U is a random number in [0, 1). Squaring is what relates radius to area, so taking the square root cancels that bias and gives a truly area-uniform spread.
Finally we convert back to x/y with basic trigonometry: x = x_center + r*cos(theta) and y = y_center + r*sin(theta).
For example, if U happens to be 0.25, then sqrt(0.25) = 0.5, so the point sits at half the radius — and over many samples the dots fill the disk evenly instead of crowding the center.