-1

我是一名工业工程师,所以你知道我的编码不是那么好,这就是我需要你帮助的原因。我的问题是我需要首先知道两个矩形之间的相交区域,以便检查是否发生重叠,这必须对 6 个矩形进行,我需要检查它们是否重叠。我的第二个问题是我在一个有明确边界的大型仓库内有 6 个矩形,我想最大化利用面积。我该如何编写代码来做到这一点。我使用了在线的波纹管代码,但我不知道如何使用它来检查 6 个矩形。

# Python program to check if rectangles overlap 
class Point: 
    def __init__(self, x, y): 
        self.x = x 
        self.y = y 
  
# Returns true if two rectangles(l1, r1)  
# and (l2, r2) overlap 
def doOverlap(l1, r1, l2, r2): 
      
    # If one rectangle is on left side of other 
    if(l1.x >= r2.x or l2.x >= r1.x): 
        return False
  
    # If one rectangle is above other 
    if(l1.y <= r2.y or l2.y <= r1.y): 
        return False
  
    return True
  
# Driver Code 
if __name__ == "__main__": 
    l1 = Point(0, 10) 
    r1 = Point(10, 0) 
    l2 = Point(5, 5) 
    r2 = Point(15, 0) 
  
    if(doOverlap(l1, r1, l2, r2)): 
        print("Rectangles Overlap") 
    else: 
        print("Rectangles Don't Overlap") 
4

1 回答 1

0

这可能会帮助您入门:

aRectangle在这里定义为 a base_point(即左下点)和 a size(它在x和中延伸的程度y)。

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

@dataclass
class Rectangle:
    base_point: Point
    size: Point

    def x_overlap(self, other: "Rectangle") -> bool:
        if self.base_point.x < other.base_point.x:
            lower = self
            higher = other
        else:
            lower = other
            higher = self

        if lower.base_point.x + lower.size.x >= higher.base_point.x:
            return True
        else:
            return False

    def y_overlap(self, other: "Rectangle") -> bool:
        if self.base_point.y < other.base_point.y:
            lower = self
            higher = other
        else:
            lower = other
            higher = self

        if lower.base_point.y + lower.size.y >= higher.base_point.y:
            return True
        else:
            return False

    def overlap(self, other: "Rectangle") -> bool:
        return self.x_overlap(other) and self.y_overlap(other)


r0 = Rectangle(base_point=Point(x=0, y=0), size=Point(x=3, y=2))
r1 = Rectangle(base_point=Point(x=2, y=1), size=Point(x=3, y=2))

print(r0.overlap(r1))

如果矩形在 x 轴和 y 轴上重叠,则它们会重叠。代码可能设计过度......您可能需要简化它以满足您的需求。但它的方式 - 我认为 - 它很好地展示了这个想法。

为了确定是否有更多的矩形重叠,您必须将所有矩形相互比较...

于 2020-10-20T09:57:16.773 回答