Similar Problems
Similar Problems not available
Generate Random Point In A Circle - Leetcode Solution
Companies:
LeetCode: Generate Random Point In A Circle Leetcode Solution
Difficulty: Medium
Topics: math
Problem Statement: Given the radius r and the center (x, y) of a circle, write a function randPoint which generates a random point inside the circle.
Solution: To generate a random point inside the circle, we can use the polar coordinates. We can select a random angle between 0 to 2π and a random radius between 0 to r. Then, we can convert the polar coordinates to cartesian coordinates to get the random point inside the circle.
Algorithm:
- Generate a random angle between 0 to 2π using the random function.
- Generate a random radius between 0 to r using the random function.
- Convert the polar coordinates to cartesian coordinates using the following formula: x = r * cos(angle) + x y = r * sin(angle) + y
- Return the generated random point (x, y).
Python Code:
import random import math
class Solution: def randPoint(self, radius: float, x_center: float, y_center: float) -> List[float]: # Generate a random angle between 0 to 2π angle = random.uniform(0, 2 * math.pi)
# Generate a random radius between 0 to r
r = radius * math.sqrt(random.uniform(0, 1))
# Convert the polar coordinates to cartesian coordinates using the above formula
x = r * math.cos(angle) + x_center
y = r * math.sin(angle) + y_center
# Return the generated random point (x, y)
return [x, y]
Time complexity: O(1) Space complexity: O(1)
Generate Random Point In A Circle Solution Code
1