|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +public class _478 { |
| 4 | + public static class Solution1 { |
| 5 | + /** |
| 6 | + * credit: https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/154037/Polar-Coordinates-10-lines |
| 7 | + * and |
| 8 | + * https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/155650/Explanation-with-Graphs-why-using-Math.sqrt() |
| 9 | + */ |
| 10 | + double radius, xCenter, yCenter; |
| 11 | + |
| 12 | + public Solution1(double radius, double xCenter, double yCenter) { |
| 13 | + this.radius = radius; |
| 14 | + this.xCenter = xCenter; |
| 15 | + this.yCenter = yCenter; |
| 16 | + } |
| 17 | + |
| 18 | + public double[] randPoint() { |
| 19 | + double len = Math.sqrt(Math.random()) * radius; |
| 20 | + double degree = Math.random() * 2 * Math.PI; |
| 21 | + double x = xCenter + len * Math.cos(degree); |
| 22 | + double y = yCenter + len * Math.sin(degree); |
| 23 | + return new double[]{x, y}; |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + public static class Solution2 { |
| 28 | + /** |
| 29 | + * How to know one point is within a circle: |
| 30 | + * https://www.geeksforgeeks.org/find-if-a-point-lies-inside-or-on-circle/ |
| 31 | + */ |
| 32 | + double top; |
| 33 | + double bottom; |
| 34 | + double left; |
| 35 | + double right; |
| 36 | + double rad; |
| 37 | + double xCenter; |
| 38 | + double yCenter; |
| 39 | + |
| 40 | + public Solution2(double radius, double xCenter, double yCenter) { |
| 41 | + this.rad = radius; |
| 42 | + this.top = yCenter + radius; |
| 43 | + this.bottom = yCenter - radius; |
| 44 | + this.left = xCenter - radius; |
| 45 | + this.right = xCenter + radius; |
| 46 | + this.xCenter = xCenter; |
| 47 | + this.yCenter = yCenter; |
| 48 | + } |
| 49 | + |
| 50 | + public double[] randPoint() { |
| 51 | + double[] result = new double[2]; |
| 52 | + result[0] = (Math.random() * (right - left)) + left; |
| 53 | + result[1] = (Math.random() * (top - bottom)) + bottom; |
| 54 | + while (Math.pow(result[0] - xCenter, 2.0) + Math.pow(result[1] - yCenter, 2.0) > Math.pow(rad, 2.0)) { |
| 55 | + result[0] = (Math.random() * (right - left)) + left; |
| 56 | + result[1] = (Math.random() * (top - bottom)) + bottom; |
| 57 | + } |
| 58 | + return result; |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments