标签:p1 一个点 个点 Point Golang 矩形 type struct
【题目】
在二维坐标系中,所有的值都是double类型,那么一个矩形可以由4个点来代表,(x 1,y 1)为最左的点、(x 2,y 2)为最上的点、(x 3,y 3)为最下的点、(x 4,y 4)为最右的点。给定4个点代表的矩形,再给定一个点(x ,y ),判断(x ,y )是否在矩形中。
解决方案
package main
import (
"fmt"
"math"
)
type Point struct {
x float64
y float64
}
type Rectangle struct {
point1 Point
point2 Point
point3 Point
point4 Point
}
// 平行于坐标轴的矩形
func isInside(p1, p4, p Point) bool {
if p.x <= p1.x || p.x >= p4.x || p.y >= p1.y || p.y <= p4.y {
return false
}
return true
}
func (rec *Rectangle) IsInside(p Point) bool {
// 若是平行于坐标轴,直接按照平行坐标轴的办法处理
if rec.point1.x == rec.point3.x {
return isInside(rec.point1, rec.point4, p)
}
// 非平行的旋转到平行
roateRec := Rectangle{}
l := math.Abs(rec.point4.y - rec.point3.y)
k := math.Abs(rec.point4.x - rec.point3.x)
s := math.Sqrt(k*k + l*l)
sin := l / s
cos := s / l
roateRec.point1.x = cos*rec.point1.x + sin*rec.point1.y
roateRec.point1.y = -roateRec.point1.x*sin + roateRec.point1.y*cos
roateRec.point4.x = cos*rec.point4.x + sin*rec.point4.y
roateRec.point4.y = -roateRec.point4.x*sin + roateRec.point4.y*cos
return isInside(roateRec.point1, roateRec.point4, p)
}
func main() {
rect := Rectangle{Point{0, 1}, Point{1, 1}, Point{0, 0}, Point{1, 0}}
p := Point{0.5, 0.5}
if rect.IsInside(p) {
fmt.Println(p, "在", rect)
} else {
fmt.Println(p, "不在", rect)
}
}
标签:p1,一个点,个点,Point,Golang,矩形,type,struct 来源: https://www.cnblogs.com/taceywong/p/16485002.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。