I need a way to merge an array of rectangle objects (objects with x,y,w,h properties) only if they intersect. So for example:

merge([{x:0, y:0, w:5, h:5}, {x:1, y:1, w:5, h:5}])

would return: [{x:0, y:0, w:6, h:6}]


merge([{x:0, y:0, w:1, h:1}, {x:5, y:5, w:1, h:1}])

would return: [{x:0, y:0, w:1, h:1}, {x:5, y:5, w:1, h:1}]


merge([{x:0, y:0, w:5, h:5}, {x:1, y:1, w:5, h:5}, {x:15, y:15, w:1, h:1}])

would return: [{x:0, y:0, w:6, h:6}, {x:15, y:15, w:1, h:1}]


If two rectangles intersect, a minimum bounding rectangle should be replace the two rectangles. The list will need to be checked again after merging in case the new MBR causes intersection with other rectangles. For the life of me I can't figure it out.

Edit
Report