CC 4.0 by-sa
Blog.csdn.net/u014390748/…

Calculate the total area formed by the overlap of two rectangles formed by straight lines on a two-dimensional plane. // Each rectangle is represented by the coordinates of its lower left and upper right vertices, as shown. // Example: // Input: -3, 0, 3, 4, 0, -1, 9, 2 // Output: 45 // Description: Assume that the area of the rectangle does not exceed the range of int. var computeArea = function(x1, y1, x2, y2, x3, y3, x4, y4) { let area1 = (x2 - x1) * (y2 - y1); let area2 = (x4 - x3) * (y4 - y3); let a = twoLineSeparate(x1,x2,x3,x4) let b = twoLineSeparate(y1,y2,y3,y4) return area1 + area2 - a * b }; function twoLineSeparate(p1, p2, p3, p4){ let len1 = p2 - p1; let len2 = p4 - p3; let max = Math.max(p1, p2, p3, p4) let min = Math.min(p1, p2, p3, If (max-min >= len1 + len2){return 0 // 1 contains 2} else if (max-min === len1){return len2 // 2 contains 1} else If (max-min === len2){return len1} else {// cross len1 + len2) - (max-min)}}Copy the code

Author GitHub: github.com/cunzaizhuyi…

Video on address: www.bilibili.com/video/av631…