描述
In previous kata we have been searching for all the neighboring points in a Cartesian coordinate system. As we know each point in a coordinate system has eight neighboring points when we search it by range equal to 1, but now we will change range by third argument of our function (range is always greater than zero). For example if range = 2, count of neighboring points = 24. In this kata grid step is the same (= 1).
It is necessary to write a function that returns array of unique distances between given point and all neighboring points. You can round up the distance to 10 decimal places (as shown in the example). Distances inside list don’t have to been sorted (any order is valid).
For Example:
CartesianNeighborsDistance(3, 2, 1) -> {1.4142135624, 1.0}
CartesianNeighborsDistance(0, 0, 2) -> {1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247}
分析
关键点在于重复距离的判定。如(5, 0)和(3, 4)相对于(0, 0)距离是相等的。但是由于浮点数精度问题,浮点数的比较并不准确,导致重复距离未被发现。
我们可以将浮点数比较转变为整型的比较。这里由于(0, 0)到(x, y)的距离是
x
2
+
y
2
\sqrt{x^2+y^2}
x2+y2,如果
x
2
+
y
2
x^2+y^2
x2+y2相等,则
x
2
+
y
2
\sqrt{x^2+y^2}
x2+y2也一定相等。故我们可以对
x
2
+
y
2
x^2+y^2
x2+y2的值进行比较。
方法1:利用数组。每次查询值是否重复,遍历既有数组。
方法2:利用map。查询性能优于数组。
实现
方法1:
import "math"
func has(s []int, a int) bool {
for _, v := range s {
if v == a { return true }
}
return false
}
func CartesianNeighborsDistance(x, y, r int) ([]float64){
ret, tmp := []float64{}, []int{}
for i := 0; i <= r; i++ {
for j := i; j <= r; j++ {
if j == 0 { continue }
t := i * i + j * j
if has(tmp, t) { continue }
tmp = append(tmp, t)
ret = append(ret, math.Hypot(float64(i), float64(j)))
}
}
return ret
}
方法2:
import "math"
func CartesianNeighborsDistance(x, y, r int) []float64 {
tmp := map[int]bool{}
for i := 1; i <= r; i++ {
for j := 0; j <= i; j++ {
tmp[i * i + j * j] = true
}
}
res := make([]float64, len(tmp))
i := 0
for j := range tmp {
res[i] = math.Sqrt(float64(j))
i++
}
return res
}