如何创建矩形表单点x和y

时间:2017-01-28 14:31:14

标签: swift

我想计算区域矩形形式的点x和y

Example Picture

class Point{
    let x: Int
    let y: Int
    init(x: Int,y: Int){
        self.x = x
        self.y = y
    }
}
class Rectangle{

       func area() -> Int{
           //I have no idea
       }

}

1 个答案:

答案 0 :(得分:1)

class Point {
    let x: Int
    let y: Int
    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }
}

class Rectangle {
    let nw: Point
    let se: Point
    init(nw: Point, se: Point) {
        self.nw = nw
        self.se = se
    }

    func area() -> Int {
        return (se.y - nw.y) * (se.x - nw.x)
    }

    func containsPoint(_ p: Point) -> Bool {
        let isContainHorizontal = (nw.x <= p.x) && (p.x <= se.x )
        let isContainVertical = (nw.y <= p.y) && (p.y <= se.y)
        return isContainHorizontal && isContainVertical
    }

    func combine(_ rect: Rectangle) -> Rectangle {
        return Rectangle(nw: Point(x: max(nw.x, rect.nw.x), y: max(nw.y, rect.nw.y)), se: Point(x: min(se.x, rect.se.x), y: min(se.y, rect.se.y)))
    }
}

输出

2. 6

3. false, true

4. 1