Generate Random Point in a Circle - Problem

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].

Input & Output

Example 1 — Unit Circle at Origin
$ Input: radius = 1.0, x_center = 0.0, y_center = 0.0
Output: [0.52, -0.85] (example output)
💡 Note: Generate a random point inside unit circle centered at origin. The actual output will vary each time due to randomness, but will always satisfy x² + y² ≤ 1.
Example 2 — Larger Circle with Offset Center
$ Input: radius = 5.0, x_center = 3.0, y_center = 4.0
Output: [6.2, 1.8] (example output)
💡 Note: Generate random point in circle of radius 5 centered at (3,4). Point satisfies (x-3)² + (y-4)² ≤ 25.
Example 3 — Small Circle
$ Input: radius = 0.1, x_center = -1.0, y_center = 2.0
Output: [-0.95, 2.03] (example output)
💡 Note: Very small circle shows the algorithm works for any radius size. Point is within 0.1 units of center (-1, 2).

Constraints

  • 0 < radius ≤ 108
  • -107 ≤ x_center, y_center ≤ 107
  • At most 3 × 104 calls will be made to randPoint

Visualization

Tap to expand
Generate Random Point in a Circle INPUT (x_center, y_center) radius radius = 1.0 x_center = 0.0 y_center = 0.0 ALGORITHM STEPS 1 Generate random r r = sqrt(random()) * radius 2 Generate random angle theta = random() * 2 * PI 3 Convert to Cartesian x = r * cos(theta) y = r * sin(theta) 4 Add center offset x = x + x_center y = y + y_center (x,y) θ r FINAL RESULT (0.52, -0.85) x y [0.52, -0.85] OK - Valid Point! Key Insight: Using sqrt(random()) for radius ensures UNIFORM distribution. Simple r = random() * radius would cluster points near the center because inner circles have less area than outer ones. The sqrt compensates for the area increase as radius grows (Area = PI * r^2). TutorialsPoint - Generate Random Point in a Circle | Optimal Solution (Polar Coordinates)
Asked in
Google 12 Facebook 8 Amazon 6 Microsoft 4
32.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen