#478
Medium Algorithms Generate random point in a circle
Math Geometry Rejection Sampling Randomized
42.5% acceptance
Jan 13, 2026
480
783
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].
Solution
Rust
Time O(n)
Space O(n)
use rand::Rng;
struct Solution {
radius: f64,
x_center: f64,
y_center: f64,
}
impl Solution {
fn new(radius: f64, x_center: f64, y_center: f64) -> Self {
Solution {
radius,
x_center,
y_center,
}
}
fn rand_point(&self) -> Vec<f64> {
let mut rng = rand::rng();
loop {
let x = rng.random_range(-self.radius..=self.radius);
let y = rng.random_range(-self.radius..=self.radius);
if x * x + y * y <= self.radius * self.radius {
return vec![self.x_center + x, self.y_center + y];
}
}
}
}