1. 程式人生 > >478.在圓內隨機生成點

478.在圓內隨機生成點

給定圓的半徑和圓心的 x、y 座標,寫一個在圓中產生均勻隨機點的函式 randPoint 。

說明:

  1. 輸入值和輸出值都將是浮點數
  2. 圓的半徑和圓心的 x、y 座標將作為引數傳遞給類的建構函式。
  3. 圓周上的點也認為是在圓中。
  4. randPoint 返回一個包含隨機點的x座標和y座標的大小為2的陣列。

示例 1:

輸入: 
["Solution","randPoint","randPoint","randPoint"]
[[1,0,0],[],[],[]]
輸出: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]

示例 2:

輸入: 
["Solution","randPoint","randPoint","randPoint"]
[[10,5,-7.5],[],[],[]]
輸出: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]

輸入語法說明:

輸入是兩個列表:呼叫成員函式名和呼叫的引數。Solution 的建構函式有三個引數,圓的半徑、圓心的 x 座標、圓心的 y 座標。randPoint 沒有引數。輸入引數是一個列表,即使引數為空,也會輸入一個 [] 空列表。

class Solution {
public:
    Solution(double radius, double x_center, double y_center) {
        r = radius; centerX = x_center; centerY = y_center;
    }
    
    vector<double> randPoint() {
       double theta = 2 * M_PI * ((double)rand() / RAND_MAX);
        double len = sqrt((double)rand() / RAND_MAX) * r;
        return {centerX + len * cos(theta), centerY + len * sin(theta)};
    }

private:
    double r, centerX, centerY;
};

/**
 * 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();
 */