[英]How can I find the least rect, which contains all points or the point symmetrical to the y=x axis?
I have a set of points (x,y). 我有一组点(x,y)。 How can I find the smallest rectangle (edges are perpendicular to the axis of the coordinate system) that contains these points or points symmetrical to the y=x axis?
如何找到包含这些点或与y = x轴对称的点的最小矩形(边与坐标系的轴垂直)? Not all the points have to be mirror images at the same time, so it is possible to have some normal and some symmetrical points to the original ones.
并非所有的点都必须同时是镜像的,因此可以对原始点具有一些法线和对称点。
You could solve this using the brute-force O(n*2^n)
approach: define your points as some class/structure which, in addition to the (x,y)
coordinates of your point, also holds a boolean mirrored
state. 您可以使用蛮力
O(n*2^n)
方法解决此问题:将点定义为某些类/结构,除了点的(x,y)
坐标外,还保留布尔mirrored
状态。 For n
number of points, loop over all the 2^n
possible set of states of this set of points. 对于
n
个点,循环遍历该点集的所有2^n
个状态集。 For each set of states, calculate the circumference ( 2x+2y
) of the bounding rectangle. 对于每个状态集,计算边界矩形的周长(
2x+2y
)。
Below follows this solution implemented in Swift. 下面是在Swift中实现的此解决方案。 If you choose to use this brute-force approach, hopefully you can translate it into your language of choice.
如果选择使用这种蛮力方法,希望可以将其翻译成您选择的语言。
Point container and help functions: 点容器和帮助功能:
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])
}
}
Main function and an example 主要功能和实例
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.