Go语言实现Cartesian neighbors distance

描述

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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值