-
Notifications
You must be signed in to change notification settings - Fork 778
/
Generate Random Point in a Circle
60 lines (50 loc) · 1.77 KB
/
Generate Random Point in a Circle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Company Tags : Please let me know when you get it
Leetcode Link : https://leetcode.com/problems/generate-random-point-in-a-circle/
*/
//Approach-1 (Non Mathematical)
class Solution {
public:
double r;
double x;
double y;
Solution(double radius, double x_center, double y_center) {
r = radius;
x = x_center;
y = y_center;
}
vector<double> randPoint() {
double x_, y_;
do{
double rand_double_x = (double)rand() / RAND_MAX; // Gets random double between [0,1]
double rand_double_y = (double)rand() / RAND_MAX;
x_ = (2*(rand_double_x) - 1.0) * r; //To get [-1, 1]
y_ = (2*(rand_double_y) - 1.0) * r; //To get [-1, 1]
} while(x_*x_ + y_*y_ > r*r);
return {x+x_, y+y_};
}
};
//Approach-2 (Mathematical)
class Solution {
public:
double x_r, y_r, rad;
Solution(double radius, double x_center, double y_center) {
x_r = x_center;
y_r = y_center;
rad = radius;
}
vector<double> randPoint() {
//we need to return (x_r + l*cos(@), y_r + l*sin(@))
//Let's find a random l first;
double l;
//l = (double)rand()/RAND_MAX*rad; No this because you will get densely populated points near origin only
l = sqrt((double)rand()/RAND_MAX)*rad;
//Let's find a random @
double theta;
theta = (double)rand()/RAND_MAX *2*3.141592653589793238;
//What that strange line above ? :-(
//Ans : rand()/RAND_MAX returns number between [0,1], and we want to get @ between [0, 360 degree] i.e. [0,2*pie]
//So, we multiply it by 2*pie :-)
return {x_r + l*cos(theta), y_r+l*sin(theta)};
}
};