1. 题目
给定圆的半径和圆心的 x、y 坐标,写一个在圆中产生均匀随机点的函数 randPoint 。
说明:
- 输入值和输出值都将是浮点数。
- 圆的半径和圆心的 x、y 坐标将作为参数传递给类的构造函数。
- 圆周上的点也认为是在圆中。
- randPoint 返回一个包含随机点的x坐标和y坐标的大小为2的数组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-random-point-in-a-circle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 找到 sinθ,cosθsinθ, cosθsinθ,cosθ 在 [-1,1] 上的随机位置,如果在单位圆内就输出(概率78.5%),否则继续找
class Solution {double r;double x, y;double cos_theta, sin_theta;
public:Solution(double radius, double x_center, double y_center) {r = radius;x = x_center;y = y_center;}vector<double> randPoint() {do{cos_theta = 2*(double)rand()/RAND_MAX - 1;sin_theta = 2*(double)rand()/RAND_MAX - 1;}while(sin_theta*sin_theta + cos_theta*cos_theta > 1);//在圆外return {x+r*cos_theta, y+r*sin_theta};}
};