Generate Random Point in a Circle

medium math random

Problem

Implement a class that, given radius and center, returns a uniformly random point in the circle.

Inputradius = 1.0, x_center = 0, y_center = 0
Output"(0.0123, -0.4567)"
Use r = R · √U₁ and θ = 2π · U₂ for uniform sampling.

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) };
    }
};
Time: O(1) per sample Space: O(1)