Skip to content

Instantly share code, notes, and snippets.

@alopatindev
Last active February 10, 2016 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alopatindev/cfda3008a6f48ee7ecc4 to your computer and use it in GitHub Desktop.
Save alopatindev/cfda3008a6f48ee7ecc4 to your computer and use it in GitHub Desktop.
CommonRectsArea.scala
// 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