Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
OOP plague solution in Clear category for Rectangles Union by quarkov
"""
This solution is intended to demonstrate a good use of OOP (I hope).
The basic concept is that any shape can be represented as the set of square cells with a specified resolution.
For this particular task we consider those square cells have dims 1x1.
Further, we define the basic Shape class and its successor - the Rectangle class - which instances will contain
all of their cells in their Rectangle.cells attribute.
Then we define the Surface class which we will use to put our rectangles onto it.
After, we only need to sum up the amount of it's "covered" cells.
"""
from itertools import product
class Shape: pass
class Rectangle(Shape):
def __init__(self, x1, y1, x2, y2):
self.cells = {cell for cell in product(range(x1, x2), range(y1, y2))}
class Surface:
def __init__(self):
self.cells = set()
def add_obj(self, obj):
if issubclass(type(obj), Shape):
self.cells |= obj.cells
def area(self):
return len(self.cells)
def rectangles_union(rectangles):
s = Surface()
[s.add_obj(Rectangle(*line)) for line in rectangles]
return s.area()
March 16, 2019
Comments: