欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

478. 在圆内随机生成点/C++

程序员文章站 2022-05-22 13:06:32
...

478. 在圆内随机生成点/C++
拒绝采样:如果生成的点不符合条件就再生成一次,直至生成的点符合条件

rand() 返回一随机数值的范围在 0 至 RAND_MAX 间。
(double)rand()/RAND_MAX就是0~1.0
2 * (double)rand()/RAND_MAX - 1.0就是-1.0~1.0

class Solution {
public:
    Solution(double radius, double x_center, double y_center)
    		:r(radius),xc(x_center),yc(y_center) {}
    
    vector<double> randPoint() {
        while(true){
            double x = (2 * (double)rand()/RAND_MAX - 1.0) * r;
            double y = (2 * (double)rand()/RAND_MAX - 1.0) * r;
            if (x * x + y * y <= r * r) 
                return {xc + x, yc + y};
        }
    }
    
private:
    double r,xc,yc;
};
/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(radius, x_center, y_center);
 * vector<double> param_1 = obj->randPoint();
 */