Header Ad

Leetcode Generate Random Point in a Circle problem solution

In this Leetcode Generate Random Point in a Circle problem solution 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].

Leetcode Generate Random Point in a Circle problem solution


Problem solution in Python.

class Solution(object):

    def __init__(self, radius, x_center, y_center):
        """
        :type radius: float
        :type x_center: float
        :type y_center: float
        """
        self.radius = radius
        self.x_center = x_center
        self.y_center = y_center
        

    def randPoint(self):
        """
        :rtype: List[float]
        """
        theta = 2*math.pi*random.random()
        r = self.radius * math.sqrt(random.random())
        x = self.x_center + r * math.cos(theta)
        y = self.y_center + r * math.sin(theta)
        return [x, y]



Problem solution in Java.

public class Solution {
    double radius;
    double xCentre;
    double yCentre;

    public Solution(double radius, double x_center, double y_center) {
        this.radius = radius;
        this.xCentre = x_center;
        this.yCentre = y_center;
    }

    public double[] randPoint() {
        double randomRadius = Math.sqrt(Math.random()) * radius;
        double angle = Math.random() * 2 * Math.PI;
        double x = xCentre + randomRadius * Math.cos(angle);
        double y = yCentre + randomRadius * Math.sin(angle);
        return new double[]{x, y};
    }
}


Problem solution in C++.

class Solution {
public:
    double r;
    double x;
    double y;
    Solution(double radius, double x_center, double y_center) {
        r = radius;
        x = x_center;
        y = y_center;
    }
    
    vector<double> randPoint() {
        double x_, y_;
        
        do{
            double rand_double_x = (double)rand() / RAND_MAX; // Gets random double between [0,1]
            double rand_double_y = (double)rand() / RAND_MAX;
            x_ = (2*(rand_double_x) - 1.0) * r;   //To get [-1, 1]
            y_ = (2*(rand_double_y) - 1.0) * r;   //To get [-1, 1]
        } while(x_*x_ + y_*y_ > r*r);
        
        return {x+x_, y+y_};
    }
};


Post a Comment

0 Comments