mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-12 14:42:01 +00:00
good good study, day day up!
This commit is contained in:
42
vendor/gopl.io/ch6/geometry/geometry.go
generated
vendored
Normal file
42
vendor/gopl.io/ch6/geometry/geometry.go
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 156.
|
||||
|
||||
// Package geometry defines simple types for plane geometry.
|
||||
//!+point
|
||||
package geometry
|
||||
|
||||
import "math"
|
||||
|
||||
type Point struct{ X, Y float64 }
|
||||
|
||||
// traditional function
|
||||
func Distance(p, q Point) float64 {
|
||||
return math.Hypot(q.X-p.X, q.Y-p.Y)
|
||||
}
|
||||
|
||||
// same thing, but as a method of the Point type
|
||||
func (p Point) Distance(q Point) float64 {
|
||||
return math.Hypot(q.X-p.X, q.Y-p.Y)
|
||||
}
|
||||
|
||||
//!-point
|
||||
|
||||
//!+path
|
||||
|
||||
// A Path is a journey connecting the points with straight lines.
|
||||
type Path []Point
|
||||
|
||||
// Distance returns the distance traveled along the path.
|
||||
func (path Path) Distance() float64 {
|
||||
sum := 0.0
|
||||
for i := range path {
|
||||
if i > 0 {
|
||||
sum += path[i-1].Distance(path[i])
|
||||
}
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
//!-path
|
Reference in New Issue
Block a user