判斷一個點是否在矩形內部【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)

	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章