I wrote this code that checks if a list of boxes overlap with each other. This seems very insufficient though because I have to loop over each box multiplied by all of the other boxes. It there a better way to do this?
For simplicity sake and broader audience I wrote this in Python but the final implementation will be in AutoLISP because I'm using this inside of AutoCAD. For that reason I'm looking for a more general solution/algorithm that will work in any language and doesn't rely on any libraries.
from random import *
from collections import namedtuple
Point = namedtuple("Point", "x y")
class Box:
def __init__(self):
center = Point(x = randint(0, 100), y = randint(0, 100))
self.UpperLeft = Point(center.x - 2, center.y + 2)
self.UpperRight = Point(center.x + 2, center.y + 2)
self.LowerRight = Point(center.x + 2, center.y - 2)
self.LowerLeft = Point(center.x - 2, center.y - 2)
def __str__(self):
return f"Box LL: {self.LowerLeft.x},{self.LowerLeft.y} and UR: {self.UpperRight.x},{self.UpperRight.y}"
def Overlaps(self, box):
if self.LowerLeft.x < box.UpperLeft.x < self.UpperRight.x and \
self.LowerLeft.y < box.UpperLeft.y < self.UpperRight.y :
return True
if self.LowerLeft.x < box.UpperRight.x < self.UpperRight.x and \
self.LowerLeft.y < box.UpperRight.y < self.UpperRight.y :
return True
if self.LowerLeft.x < box.LowerRight.x < self.UpperRight.x and \
self.LowerLeft.y < box.LowerRight.y < self.UpperRight.y :
return True
if self.LowerLeft.x < box.LowerLeft.x < self.UpperRight.x and \
self.LowerLeft.y < box.LowerLeft.y < self.UpperRight.y :
return True
return False
boxes = [Box() for _ in range(300)]
for thisBox in boxes:
multiplesFound = 0
for otherBox in boxes:
if thisBox is otherBox:
continue
elif thisBox.Overlaps(otherBox):
print(f"{thisBox} overlaps with {otherBox}")
multiplesFound += 1
if multiplesFound >= 1:
pass # highlight overlapping objects