使用 C++ 在圆内生成随机点

c++server side programmingprogramming更新于 2025/4/15 5:52:17

假设我们有一个圆心的半径和 x-y 位置,我们必须编写一个名为 randPoint() 的函数,该函数在圆内生成一个均匀的随机点。因此,我们必须牢记一些要点 −

  • 输入和输出值都是浮点数。
  • 圆心的半径和 x-y 位置被传递到类构造函数中。
  • 圆周上的点被视为在圆内。
  • randPoint() 按顺序返回随机点的 x 位置和 y 位置。

因此,如果输入为 [10, 5,-7.5],则可能会生成一些随机点,如 [11.15792,-8.54781]、[2.49851,-16.27854]、[11.16325,-12.45479]。

为了解决这个问题,我们将遵循以下步骤−

  • 定义一个名为 uniform() 的方法。它将按如下方式工作 −
  • 返回 random_number/MAX RANDOM
  • 通过初始化程序初始化 rad 和中心坐标
  • randPoint 将按如下方式工作 −
  • theta = 2*Pi*uniform()
  • r := square root of uniform()
  • 返回一对,如 (center_x + r*radius*cos(theta), center_y + r*radius*sin(theta))

让我们看看下面的实现以便更好地理解 −

示例

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   const double PI = 3.14159265358979732384626433832795;
   double m_radius, m_x_center, m_y_center;
   double uniform() {
      return (double)rand() / RAND_MAX;
   }
   Solution(double radius, double x_center, double y_center) {
      srand(time(NULL));
      m_radius = radius; m_x_center = x_center; m_y_center = y_center;
   }
   vector<double> randPoint() {
      double theta = 2 * 3.14159265358979323846264 * uniform();
      double r = sqrt(uniform());
      return vector<double>{
         m_x_center + r * m_radius * cos(theta),
         m_y_center + r * m_radius * sin(theta)
      };
   }
};
main(){
   Solution ob(10, 5, 7);
   print_vector(ob.randPoint());
   print_vector(ob.randPoint());
   print_vector(ob.randPoint());
}

输入

Pass 10, 5, 7 into constructor
Call randPoint() three times

输出

[1.5441, 9.14912, ]
[-1.00029, 13.9072, ]
[10.2384, 6.49618, ]

相关文章