From 7bafaed0728e5b21cb3cb12b4d7073af56461764 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Fri, 9 Jun 2023 16:04:13 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BA=8C=E7=BB=B4=E6=95=B0=E7=BB=84=E8=BE=85?= =?UTF-8?q?=E5=8A=A9=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/g2d/g2d.go | 40 ++++++++++++++++++++++++++++++++++++++++ utils/g2d/g2d_test.go | 13 +++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 utils/g2d/g2d_test.go diff --git a/utils/g2d/g2d.go b/utils/g2d/g2d.go index 906926c..0b4322f 100644 --- a/utils/g2d/g2d.go +++ b/utils/g2d/g2d.go @@ -32,3 +32,43 @@ func GetAdjacentPositions[T any](matrix [][]T, x, y int) (result [][2]int) { } return } + +// GetAdjacentPositionsWithContinuousPosition 获取一个连续位置的矩阵中,特定位置相邻的最多四个方向的位置 +func GetAdjacentPositionsWithContinuousPosition[T any](matrix []T, width, pos int) (result []int) { + size := len(matrix) + if up := pos - width; up >= 0 { + result = append(result, up) + } + if down := pos + width; down < size { + result = append(result, size) + } + if left := pos - 1; pos >= 0 { + result = append(result, left) + } + if right := pos + 1; right < size { + result = append(result, right) + } + return +} + +// PositionToInt 将坐标转换为二维数组的顺序位置 +func PositionToInt(width, x, y int) int { + return y*width + x +} + +// PositionIntToXY 通过宽度将一个二维数组的顺序位置转换为xy坐标 +func PositionIntToXY(width, pos int) (x, y int) { + x = pos % width + y = pos / width + return x, y +} + +// PositionIntGetX 通过宽度将一个二维数组的顺序位置转换为X坐标 +func PositionIntGetX(width, pos int) int { + return pos % width +} + +// PositionIntGetY 通过宽度将一个二维数组的顺序位置转换为Y坐标 +func PositionIntGetY(width, pos int) int { + return pos / width +} diff --git a/utils/g2d/g2d_test.go b/utils/g2d/g2d_test.go new file mode 100644 index 0000000..b3aa56b --- /dev/null +++ b/utils/g2d/g2d_test.go @@ -0,0 +1,13 @@ +package g2d + +import ( + "fmt" + "testing" +) + +func TestPositionIntToXY(t *testing.T) { + pos := PositionToInt(9, 7, 8) + fmt.Println(pos) + fmt.Println(PositionIntToXY(9, pos)) + +}