[英]How do i find the smallest point P(x,y) containing triangle from a bunch of points?
[英]How can I find the least rect, which contains all points or the point symmetrical to the y=x axis?
我有一組點(x,y)。 如何找到包含這些點或與y = x軸對稱的點的最小矩形(邊與坐標系的軸垂直)? 並非所有的點都必須同時是鏡像的,因此可以對原始點具有一些法線和對稱點。
您可以使用蠻力O(n*2^n)
方法解決此問題:將點定義為某些類/結構,除了點的(x,y)
坐標外,還保留布爾mirrored
狀態。 對於n
個點,循環遍歷該點集的所有2^n
個狀態集。 對於每個狀態集,計算邊界矩形的周長( 2x+2y
)。
下面是在Swift中實現的此解決方案。 如果選擇使用這種蠻力方法,希望可以將其翻譯成您選擇的語言。
點容器和幫助功能:
struct Point {
private var xOrig : Double
private var yOrig : Double
private var mirrored = false
var x : Double { return mirrored ? yOrig : xOrig }
var y : Double { return mirrored ? xOrig : yOrig }
init(_ x: Double, _ y: Double) {
xOrig = x
yOrig = y
}
mutating func setState(state: Bool) {
mirrored = state
}
}
func boundingBoxCircumference(points: [Point]) -> Double {
let xMax = points.maxElement { $0.x < $1.x }?.x ?? 0.0
let xMin = points.minElement { $0.x < $1.x }?.x ?? 0.0
let yMax = points.maxElement { $0.y < $1.y }?.y ?? 0.0
let yMin = points.minElement { $0.y < $1.y }?.y ?? 0.0
return 2*((xMax - xMin) + (yMax - yMin))
}
func setMirroredStates(inout points: [Point], states: [Bool]) {
for i in 0..<points.count {
points[i].setState(states[i])
}
}
主要功能和實例
func findSmallestBox(var points: [Point]) -> Double {
var smallestBox = Double.infinity
for i in 0..<Int(pow(2,Double(points.count))) {
smallestBox = min(smallestBox, boundingBoxCircumference(points))
var binString = String(i, radix: 2)
if let a = Optional(points.count - binString.characters.count) where a > 0 {
binString = "".stringByPaddingToLength(a, withString: "0", startingAtIndex: 0) + binString
}
let pointStates = Array(binString.characters).map { String($0) == "1" }
setMirroredStates(&points, states: pointStates)
}
return smallestBox
}
var myPoints : [Point] = [Point(1,2), Point(-4,3), Point(7,-5), Point(5,4), Point(-5, -1)]
print(findSmallestBox(myPoints)) // 34
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.