题目

Given the radius and x-y positions of the center of a circle, write a function randPoint which generates a uniform random point in the circle.

Note:

  1. input and output values are in floating-point.
  2. radius and x-y position of the center of the circle is passed into the class constructor.
  3. a point on the circumference of the circle is considered to be in the circle.
  4. randPoint returns a size 2 array containing x-position and y-position of the random point, in that order.

Example 1:

  1. Input:
  2. ["Solution","randPoint","randPoint","randPoint"]
  3. [[1,0,0],[],[],[]]
  4. Output: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]

Example 2:

  1. Input:
  2. ["Solution","randPoint","randPoint","randPoint"]
  3. [[10,5,-7.5],[],[],[]]
  4. Output: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]

Explanation of Input Syntax:

The input is two lists: the subroutines called and their arguments. Solution‘s constructor has three arguments, the radius, x-position of the center, and y-position of the center of the circle. randPoint has no arguments. Arguments are always wrapped with a list, even if there aren’t any.


题意

在圆内随机生成一个点。

思路

极坐标容易处理:生成一个随机的角度rad,一个随机的长度len,len在0-radius之间,那么得到的随机点就是(lencos(rad) + x, lensin(rad) + y)。问题在于如果len直接由radius乘一个0-1的随机数random生成,最后得到的结果并不是对于面积等概率的。举个例子,如果要在半径为R的圆中取一点,使该点正好在半径为R/2的同心圆中,概率为1/4而不是1/2。因此应当先对random去平方根,再与半径相乘来得到len值。


代码实现

Java

  1. class Solution {
  2. private double r, x, y;
  3. private Random random;
  4. public Solution(double radius, double x_center, double y_center) {
  5. r = radius;
  6. x = x_center;
  7. y = y_center;
  8. random = new Random();
  9. }
  10. public double[] randPoint() {
  11. double len = Math.sqrt(random.nextDouble()) * r;
  12. double rad = random.nextDouble() * Math.PI * 2;
  13. return new double[]{len * Math.cos(rad) + x, len * Math.sin(rad) + y};
  14. }
  15. }