สมมติว่าเรามีรัศมีและตำแหน่ง 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 จะทำงานดังนี้ -
- ธีต้า =2*Pi*uniform()
- r :=รากที่สองของชุดยูนิฟอร์ม()
- คืนค่าคู่เช่น (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, ]