Last active
February 10, 2016 00:56
-
-
Save alopatindev/cfda3008a6f48ee7ecc4 to your computer and use it in GitHub Desktop.
CommonRectsArea.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// find a common area of two (probably intersected) rectangles | |
object CommonRectsArea extends App { | |
type Coord = (Int, Int) | |
class Rect(val bottomLeft: Coord, val topRight: Coord) { | |
def width: Int = topRight._1 - bottomLeft._1 | |
def height: Int = topRight._2 - bottomLeft._2 | |
def area: Int = width * height | |
} | |
private def intersectionArea(a: Rect, b: Rect): Int = { | |
val w = (a.bottomLeft._1 until a.topRight._1) intersect (b.bottomLeft._1 until b.topRight._1) | |
val h = (a.bottomLeft._2 until a.topRight._2) intersect (b.bottomLeft._2 until b.topRight._2) | |
w.size * h.size | |
} | |
def commonArea(bottomLeftA: Coord, topRightA: Coord, bottomLeftB: Coord, topRightB: Coord): Int = | |
commonArea( | |
new Rect(bottomLeftA, topRightA), | |
new Rect(bottomLeftB, topRightB) | |
) | |
def commonArea(a: Rect, b: Rect): Int = | |
a.area + b.area - intersectionArea(a, b) | |
assert( | |
commonArea( | |
(0, 0), (3, 2), (2, 1), (4, 3) | |
) == 9 | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment