forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_478.java
63 lines (57 loc) · 2.17 KB
/
_478.java
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
61
62
63
package com.fishercoder.solutions;
public class _478 {
public static class Solution1 {
/**
* credit: https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/154037/Polar-Coordinates-10-lines
* and
* https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/155650/Explanation-with-Graphs-why-using-Math.sqrt()
*/
double radius;
double xCenter;
double yCenter;
public Solution1(double radius, double xCenter, double yCenter) {
this.radius = radius;
this.xCenter = xCenter;
this.yCenter = yCenter;
}
public double[] randPoint() {
double len = Math.sqrt(Math.random()) * radius;
double degree = Math.random() * 2 * Math.PI;
double x = xCenter + len * Math.cos(degree);
double y = yCenter + len * Math.sin(degree);
return new double[]{x, y};
}
}
public static class Solution2 {
/**
* How to know one point is within a circle:
* https://www.geeksforgeeks.org/find-if-a-point-lies-inside-or-on-circle/
*/
double top;
double bottom;
double left;
double right;
double rad;
double xCenter;
double yCenter;
public Solution2(double radius, double xCenter, double yCenter) {
this.rad = radius;
this.top = yCenter + radius;
this.bottom = yCenter - radius;
this.left = xCenter - radius;
this.right = xCenter + radius;
this.xCenter = xCenter;
this.yCenter = yCenter;
}
public double[] randPoint() {
double[] result = new double[2];
result[0] = (Math.random() * (right - left)) + left;
result[1] = (Math.random() * (top - bottom)) + bottom;
while (Math.pow(result[0] - xCenter, 2.0) + Math.pow(result[1] - yCenter, 2.0) > Math.pow(rad, 2.0)) {
result[0] = (Math.random() * (right - left)) + left;
result[1] = (Math.random() * (top - bottom)) + bottom;
}
return result;
}
}
}