判断一个点是否在矩形内部【Golang实现】
【题目】
在二维坐标系中,所有的值都是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)
}
}
还真有人点开啊🤣随意随意😂