Software Engineering

Calculating Cartesian Neighbors Distance in Golang

Calculating Cartesian Neighbors Distance in Golang
Written by admin


The problem

We’ve got been looking for all of the neighboring factors in a Cartesian coordinate system. As we all know every level in a coordinate system has eight neighboring factors after we search it by vary equal to 1, however now we are going to change the vary by the third argument of our operate (vary is at all times larger than zero). For instance, if vary = 2, rely of neighboring factors = 24. On this problem, a grid step is identical (= 1).

It’s essential to jot down a operate that returns an array of distinctive distances between the given level and all neighboring factors. You may spherical up the gap to 10 decimal locations (as proven within the instance). Distances contained in the record don’t must be sorted (any order is legitimate).

Examples:

CartesianNeighborsDistance(3, 2, 1) -> {1.4142135624, 1.0}
CartesianNeighborsDistance(0, 0, 2) -> {1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247}

The answer in Golang

Possibility 1:

package deal resolution
import "math"
func CartesianNeighborsDistance(x, y, r int) []float64 {
    squaredDistances := make(map[int]struct{})
    for dy := 1; dy <= r; dy++ {
        for dx := 0; dx <= dy; dx++ {
            squaredDistances[dx * dx + dy * dy] = struct{}{}
        }
    }
    consequence := make([]float64, len(squaredDistances))
    i := 0
    for ok := vary squaredDistances {
        consequence[i] = math.Sqrt(float64(ok))
        i++
    }
    return consequence
}

Possibility 2:

package deal resolution
import "math"
func CartesianNeighborsDistance(x, y, r int) []float64 {
    squaredDistances := make(map[int]struct{})
    for dy := 1; dy <= r; dy++ {
        for dx := 0; dx <= dy; dx++ {
            squaredDistances[dx * dx + dy * dy] = struct{}{}
        }
    }
    consequence := make([]float64, len(squaredDistances))
    i := 0
    for ok := vary squaredDistances {
        consequence[i] = math.Sqrt(float64(ok))
        i++
    }
    return consequence
}

Possibility 3:

package deal resolution
import "math"
func CartesianNeighborsDistance(x, y, r int) (dists []float64){
  distSqrMap := make(map[int]struct{})
  for x := 1; x <= r; x++ {
    for y := 0; y <= x; y++ {
      distSqrMap[x*x + y*y] = struct{}{}
    }
  }
  for distSquared := vary distSqrMap {
    dists = append(dists, math.Sqrt(float64(distSquared)))
  }
  return
}

Check circumstances to validate our resolution

package deal solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"      
)
func dotest(x, y, r int, exp []float64){
  var act = CartesianNeighborsDistance(x, y, r)
  var eq = AlmostEquals(SortedList(act), exp)
  Anticipate(eq).To(Equal("True"))
}
var _ = Describe("Exams", func() {     
   It("ExampleTest", func() {
     dotest(3, 2, 1, []float64{1.0, 1.4142135624})
   })
})

About the author

admin

Leave a Comment