478. 在圆内随机生成点
给定圆的半径和圆心的位置,实现函数 randPoint ,在圆中产生均匀随机点。
实现 Solution 类:
Solution(double radius, double x_center, double y_center) 用圆的半径 radius 和圆心的位置 (x_center, y_center) 初始化对象
randPoint() 返回圆内的一个随机点。圆周上的一点被认为在圆内。答案作为数组返回 [x, y] 。
示例 1:
输入:
[“Solution”,“randPoint”,“randPoint”,“randPoint”]
[[1.0, 0.0, 0.0], [], [], []]
输出: [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]
解释:
Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint ();//返回[-0.02493,-0.38077]
solution.randPoint ();//返回[0.82314,0.38945]
solution.randPoint ();//返回[0.36572,0.17248]
这个题目还是很应该去学习一下这个方法,很不错的一个构造随机数的方法,解题代码如下:
typedef struct {
double radius;
double x_center;
double y_center;
} Solution;
Solution* solutionCreate(double radius, double x_center, double y_center) {
Solution * S=(Solution *)malloc(sizeof(Solution));
S->radius=radius;
S->x_center=x_center;
S->y_center=y_center;
return S;
}
double* solutionRandPoint(Solution* obj, int* retSize) {
double *re=(double *)malloc(sizeof(double)*2);
*retSize=2;
double r=obj->radius;
while(true){
double x=((double)rand())/RAND_MAX *2*r-r;
double y=((double)rand())/RAND_MAX *2*r-r;
if(x*x+y*y<=obj->radius*obj->radius){
re[0]=x+obj->x_center;
re[1]=y+obj->y_center;
return re;
}
}
return 0;
}
void solutionFree(Solution* obj) {
free(obj);
}
/**
* Your Solution struct will be instantiated and called as such:
* Solution* obj = solutionCreate(radius, x_center, y_center);
* double* param_1 = solutionRandPoint(obj, retSize);
* solutionFree(obj);
*/