website/content.en/ChapterFour/0400~0499/0478.Generate-Random-Point-in-a-Circle.md
Given the radius and x-y positions of the center of a circle, write a function randPoint which generates a uniform random point in the circle.
Note:
randPoint returns a size 2 array containing x-position and y-position of the random point, in that order.Example 1:
Input:
["Solution","randPoint","randPoint","randPoint"]
[[1,0,0],[],[],[]]
Output: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]
Example 2:
Input:
["Solution","randPoint","randPoint","randPoint"]
[[10,5,-7.5],[],[],[]]
Output: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution's constructor has three arguments, the radius, x-position of the center, and y-position of the center of the circle. randPoint has no arguments. Arguments are always wrapped with a list, even if there aren't any.
Given the radius and the x and y coordinates of the center of a circle, write a function randPoint that generates a uniformly random point inside the circle.
Notes:
(x-a)^2+(y-b)^2 ≤ R^2, where (a,b) is the coordinate of the center of the circle, and R is the radius.rand.Float64() generates a floating-point number in the range [0.0,1.0). -R ≤ 2 * R * rand() - R < R. Use the relationship between the randomly generated point's horizontal and vertical coordinates (x,y) and the radius R. If x^2 + y^2 ≤ R^2, then the generated point is inside the circle. When finally outputting, remember to add the offset value of the center coordinates.package leetcode
import (
"math"
"math/rand"
"time"
)
type Solution struct {
r float64
x float64
y float64
}
func Constructor(radius float64, x_center float64, y_center float64) Solution {
rand.Seed(time.Now().UnixNano())
return Solution{radius, x_center, y_center}
}
func (this *Solution) RandPoint() []float64 {
/*
a := angle()
r := this.r * math.Sqrt(rand.Float64())
x := r * math.Cos(a) + this.x
y := r * math.Sin(a) + this.y
return []float64{x, y}*/
for {
rx := 2*rand.Float64() - 1.0
ry := 2*rand.Float64() - 1.0
x := this.r * rx
y := this.r * ry
if x*x+y*y <= this.r*this.r {
return []float64{x + this.x, y + this.y}
}
}
}
func angle() float64 {
return rand.Float64() * 2 * math.Pi
}
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(radius, x_center, y_center);
* param_1 := obj.RandPoint();
*/