RosettaCodeData/Task/Closest-pair-problem/Go/closest-pair-problem-1.go

47 lines
877 B
Go
Raw Permalink Normal View History

2013-04-10 12:38:42 -07:00
package main
import (
"fmt"
"math"
"math/rand"
2016-12-05 22:15:40 +01:00
"time"
2013-04-10 12:38:42 -07:00
)
type xy struct {
x, y float64
}
const n = 1000
2016-12-05 22:15:40 +01:00
const scale = 100.
2013-04-10 12:38:42 -07:00
func d(p1, p2 xy) float64 {
2016-12-05 22:15:40 +01:00
return math.Hypot(p2.x-p1.x, p2.y-p1.y)
2013-04-10 12:38:42 -07:00
}
func main() {
2016-12-05 22:15:40 +01:00
rand.Seed(time.Now().Unix())
2013-04-10 12:38:42 -07:00
points := make([]xy, n)
for i := range points {
2016-12-05 22:15:40 +01:00
points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}
2013-04-10 12:38:42 -07:00
}
p1, p2 := closestPair(points)
fmt.Println(p1, p2)
fmt.Println("distance:", d(p1, p2))
}
func closestPair(points []xy) (p1, p2 xy) {
if len(points) < 2 {
panic("at least two points expected")
}
min := 2 * scale
for i, q1 := range points[:len(points)-1] {
for _, q2 := range points[i+1:] {
if dq := d(q1, q2); dq < min {
p1, p2 = q1, q2
min = dq
}
}
}
return
}