Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
matrix 0 & 1 solution in Clear category for Rectangles Union by pokryshkin
from typing import List, Tuple
def rectangles_union(recs: List[Tuple[int]]) -> int:
if not recs: return 0
# find out ranges of x and y
min_x = min([ p[n] for n in (0,2) for p in recs])
max_x = max([ p[n] for n in (0,2) for p in recs])
min_y = min([ p[n] for n in (1,3) for p in recs])
max_y = max([ p[n] for n in (1,3) for p in recs])
# create zero-filled matrix
data = [[ 0 for _ in range(max_x-min_x)] for _ in range(max_y-min_y)]
# change 0 => 1 in area of rectangles
for rectangle in recs:
x1 = rectangle[0] - min_x
y1 = rectangle[1] - min_y
x2 = rectangle[2] - min_x
y2 = rectangle[3] - min_y
for j in range(y1,y2):
for i in range(x1,x2):
data[j][i] = 1
# calculate quantity of '1'
square = sum([value for sublist in data for value in sublist])
return square
if __name__ == '__main__':
print("Example:")
print(rectangles_union([
(6, 3, 8, 10),
(4, 8, 11, 10),
(16, 8, 19, 11)
]))
# These "asserts" are used for self-checking and not for an auto-testing
assert rectangles_union([
(6, 3, 8, 10),
(4, 8, 11, 10),
(16, 8, 19, 11)
]) == 33
assert rectangles_union([
(16, 8, 19, 11)
]) == 9
assert rectangles_union([
(16, 8, 19, 11),
(16, 8, 19, 11)
]) == 9
assert rectangles_union([
(16, 8, 16, 8)
]) == 0
assert rectangles_union([
]) == 0
print("Coding complete? Click 'Check' to earn cool rewards!")
April 26, 2021