You are given a circle represented as (x_center, y_center, radius)
. Implement a class Solution
with two methods:
__init__(self, radius: float, x_center: float, y_center: float)
: This initializes the class with the circle’s radius and center.randPoint(self) -> List[float]
: This method returns a random point inside the circle. Each point must be uniformly distributed inside the circle.Here’s the problem from LeetCode 478. Generate Random Point in a Circle:
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
pass
def randPoint(self) -> List[float]:
pass
To ensure the points are uniformly distributed inside the circle, we should follow these steps:
r
using the square root of a uniformly generated random number. This ensures uniform distribution over the area.theta
between 0 and 2*pi
.(r, theta)
to Cartesian coordinates using the formulas:
x = x_center + r * cos(theta)
y = y_center + r * sin(theta)
random
module to generate random numbers.Here’s the implementation based on the discussed strategy:
import random
import math
from typing import List
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self) -> List[float]:
# Generate a random radius with sqrt scaling to ensure uniform distribution over the area
r = self.radius * math.sqrt(random.random())
# Generate a random angle
theta = random.uniform(0, 2 * math.pi)
# Convert polar coordinates to Cartesian coordinates
x = self.x_center + r * math.cos(theta)
y = self.y_center + r * math.sin(theta)
return [x, y]
__init__
method): O(1) - It’s a straightforward assignment of values.randPoint
method): O(1) - All operations are constant time operations including random number generation and mathematical calculations.This solution efficiently ensures uniformly distributed random points inside a given circle.
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?