Leetcode 478. Generate Random Point in a Circle
You are asked to implement the Solution
class that initializes with the radius and the x-y position of the center of a circle. The class should have a method randPoint
that generates a random point within that circle.
Solution
class should look like this:class Solution {
public:
Solution(double radius, double x_center, double y_center);
vector<double> randPoint();
};
Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint(); // returns a random point in the circle [0.0,0.0] with radius 1.0
randPoint
.To generate a random point uniformly in a circle:
θ
between 0 and 2π.r
using the inverse transform sampling method where r
is adjusted by the square root of a uniform random variable to maintain uniform distribution.randPoint()
: O(1)The time complexity for generating a point is constant because it involves basic arithmetic operations and random number generation which are O(1) operations.
Here’s the implementation in C++:
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
class Solution {
private:
double radius, x_center, y_center;
public:
Solution(double radius, double x_center, double y_center)
: radius(radius), x_center(x_center), y_center(y_center) {
// Initialize random seed
std::srand(std::time(nullptr));
}
std::vector<double> randPoint() {
double theta = ((double) std::rand() / RAND_MAX) * 2 * M_PI;
double raw_r = (double) std::rand() / RAND_MAX;
double r = std::sqrt(raw_r) * radius;
double x = r * std::cos(theta) + x_center;
double y = r * std::sin(theta) + y_center;
return {x, y};
}
};
Solution
): Initializes the circle’s radius and center.randPoint
Method:
θ
between 0 and 2π.(r, θ)
to Cartesian coordinates (x, y)
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?