




Sponsored
Sponsored
Rejection sampling is a technique used to generate samples from a distribution by generating samples from a proposal distribution and then rejecting some of the samples. In the context of this problem, you can generate random points in a square that circumscribes the circle and then only accept those points that lie inside the circle.
Time Complexity: O(1) on average. Space Complexity: O(1) as no extra space is used.
1#include <random>
2#include <vector>
3#include <cmath>
4
5class Solution {
6    double radius, x_center, y_center;
7    std::default_random_engine generator;
8    std::uniform_real_distribution<double> distribution;
9
10public:
11    Solution(double radius, double x_center, double y_center) : radius(radius), x_center(x_center), y_center(y_center), distribution(-radius, radius) {}
12
13    std::vector<double> randPoint() {
14        double x, y;
15        do {
16            x = distribution(generator);
17            y = distribution(generator);
18        } while (x * x + y * y > radius * radius);
19        return {x_center + x, y_center + y};
20    }
21};This C++ solution mirrors the approach in Python, using the C++ Standard Library’s random utilities to generate points within a bounding square, ensuring uniform distribution inside the circle using rejection sampling.
Instead of generating points in a square and rejecting those outside the circle, we can directly generate points within the circle using polar coordinates. By randomly selecting an angle and a distance from the center, and then converting these polar coordinates to Cartesian coordinates, we can efficiently generate a uniform random point within the circle.
Time Complexity: O(1). Space Complexity: O(1).
1class Solution {
2    constructor(radius,
Using JavaScript, this solution similarly generates a random angle and a uniform radial distance (by taking the square root of a random value) which ensures the point falls within the circle. The Cartesian coordinates are calculated from polar form.