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:

  1. Generate a random angle between 0 to 2π using the random function.
  2. Generate a random radius between 0 to r using the random function.
  3. Convert the polar coordinates to cartesian coordinates using the following formula: x = r * cos(angle) + x y = r * sin(angle) + y
  4. 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

1Solution:
2
3#include <iostream> #include <cstdlib> #include <cmath> using namespace std; 
4
5// Function to generate a random point in a circle 
6void generateRandomPoint(double radius) 
7{ 
8    // Generate two random numbers 
9    double x = (double)(rand()) / RAND_MAX; 
10    double y = (double)(rand()) / RAND_MAX; 
11  
12    // Multiplication factor 
13    double mult = sqrt(x * x + y * y); 
14  
15    // Calculate the new coordinates 
16    x = x * radius / mult; 
17    y = y * radius / mult; 
18  
19    // Print the point 
20    cout << "(" << x << ", " << y << ")" << endl; 
21} 
22  
23// Driver code 
24int main() 
25{ 
26    // Set the seed 
27    srand(time(0)); 
28  
29    // Radius of the circle 
30    double radius = 10.0; 
31  
32    // Generate 10 random points 
33    for (int i = 0; i < 10; i++) 
34        generateRandomPoint(radius); 
35  
36    return 0; 
37}