跳到主要内容

478.在圆内随机生成点

链接:478.在圆内随机生成点
难度:Medium
标签:几何、数学、拒绝采样、随机化
简介:给定圆的半径和圆心的位置,实现函数 randPoint ,在圆中产生均匀随机点。

题解 1 - typescript

  • 编辑时间:2022-06-05
  • 执行用时:128ms
  • 内存消耗:58.3MB
  • 编程语言:typescript
  • 解法介绍:忽略边上的点。
class Solution {
constructor(public radius: number, public x_center: number, public y_center: number) {}
randPoint(): number[] {
while (true) {
const [x, y] = [
2 * Math.random() * this.radius - this.radius,
2 * Math.random() * this.radius - this.radius,
];
if (x ** 2 + y ** 2 <= this.radius * this.radius)
return [x + this.x_center, y + this.y_center];
}
}
}