Skip to content

Instantly share code, notes, and snippets.

@ahmedk92
Created August 21, 2021 21:17
Show Gist options
  • Save ahmedk92/659f114bc908842e457d9d1214fccfc7 to your computer and use it in GitHub Desktop.
Save ahmedk92/659f114bc908842e457d9d1214fccfc7 to your computer and use it in GitHub Desktop.
Rectangle Area
/*
* @lc app=leetcode id=223 lang=swift
*
* [223] Rectangle Area
*/
// @lc code=start
class Solution {
func computeArea(_ ax1: Int, _ ay1: Int, _ ax2: Int, _ ay2: Int, _ bx1: Int, _ by1: Int, _ bx2: Int, _ by2: Int) -> Int {
let rect1 = CGRect(
minX: CGFloat(ax1),
minY: CGFloat(ay1),
maxX: CGFloat(ax2),
maxY: CGFloat(ay2)
)
let rect2 = CGRect(
minX: CGFloat(bx1),
minY: CGFloat(by1),
maxX: CGFloat(bx2),
maxY: CGFloat(by2)
)
return Int(rect1.area + (rect2.area - rect1.intersection(rect2).area))
}
}
struct CGRect {
var origin: CGPoint
var size: CGSize
var minX: CGFloat { origin.x }
var minY: CGFloat { origin.y }
var maxX: CGFloat { origin.x + size.width }
var maxY: CGFloat { origin.y + size.height }
var width: CGFloat { size.width }
var height: CGFloat { size.height }
static let zero = CGRect(x: 0, y: 0, width: 0, height: 0)
static let null: CGRect = {
var rect = CGRect.zero
rect.isNull = true
return rect
}()
private(set) var isNull: Bool = false
init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
self.origin = .init(x: x, y: y)
self.size = .init(width: width, height: height)
}
init(minX: CGFloat, minY: CGFloat, maxX: CGFloat, maxY: CGFloat) {
let width = maxX - minX
let height = maxY - minY
self = .init(
x: minX,
y: minY,
width: width,
height: height
)
}
func intersection(_ rect2: CGRect) -> CGRect {
if maxX < rect2.minX || rect2.maxX < minX {
return .null
}
if maxY < rect2.minY || rect2.maxY < minY {
return .null
}
let intersectionMinX = max(minX, rect2.minX)
let intersectionMaxX = min(maxX, rect2.maxX)
let intersectionMinY = max(minY, rect2.minY)
let intersectionMaxY = min(maxY, rect2.maxY)
return .init(
minX: intersectionMinX,
minY: intersectionMinY,
maxX: intersectionMaxX,
maxY: intersectionMaxY
)
}
}
struct CGPoint {
var x: CGFloat
var y: CGFloat
}
struct CGSize {
var width: CGFloat
var height: CGFloat
}
typealias CGFloat = Double
private extension CGRect {
var area: CGFloat {
guard !isNull else { return 0 }
return width * height
}
}
// @lc code=end
@ahmedk92
Copy link
Author

ahmedk92 commented Aug 21, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment