按順時針順序排序點?給定一個x,y點數組,如何按順時針順序(圍繞它們的整體平均中心點)對該數組的點進行排序?我的目標是將點傳遞給線創建函數,以最終看起來相當“堅實”的東西,盡可能凸起,沒有相交的線。為了它的價值,我正在使用Lua,但任何偽代碼都會受到贊賞。非常感謝您的幫助!更新:作為參考,這是基于Ciamej優秀答案的Lua代碼(忽略我的“app”前綴):function appSortPointsClockwise(points) local centerPoint = appGetCenterPointOfPoints(points) app.pointsCenterPoint = centerPoint table.sort(points, appGetIsLess) return pointsendfunction appGetIsLess(a, b) local center = app.pointsCenterPoint if a.x >= 0 and b.x < 0 then return true elseif a.x == 0 and b.x == 0 then return a.y > b.y end local det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y) if det < 0 then return true elseif det > 0 then return false end local d1 = (a.x - center.x) * (a.x - center.x) + (a.y - center.y) * (a.y - center.y) local d2 = (b.x - center.x) * (b.x - center.x) + (b.y - center.y) * (b.y - center.y) return d1 > d2endfunction appGetCenterPointOfPoints(points) local pointsSum = {x = 0, y = 0} for i = 1, #points do pointsSum.x = pointsSum.x + points[i].x; pointsSum.y = pointsSum.y + points[i].y end return {x = pointsSum.x / #points, y = pointsSum.y / #points}end
3 回答

鳳凰求蠱
TA貢獻1825條經驗 獲得超4個贊
您要求的是一個稱為極坐標的系統。從笛卡爾坐標到極坐標的轉換很容易用任何語言完成。公式可以在本節中找到。
我不認識Lua,但此頁面似乎提供了此轉換的代碼段。
轉換為極坐標后,只需按角度θ進行排序。

慕的地8271018
TA貢獻1796條經驗 獲得超4個贊
解決問題的一個有趣的替代方法是找到旅行商問題(TSP)的近似最小值,即。連接所有積分的最短路線。如果你的點形成凸形,它應該是正確的解決方案,否則,它應該仍然看起來很好(“實心”形狀可以定義為具有低周長/面積比的形狀,這是我們在這里優化的) 。
您可以為TSP使用優化器的任何實現,我非常確定您可以用您選擇的語言找到它。
添加回答
舉報
0/150
提交
取消