We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
to calculate the area of a polygon when its coordinates are given we ll use shoelace formula = 0.5 * ( x1y2 − x2y1 + x2y3 − x3y2 +. . . + xny0 − x0yn)
(x1,y1), (x2,y2) => x1y2 − x2y1
(x2,y2), (x3,y3) => x2y3 − x3y2
.
.
.
(xn,yn), (x0,y0)=> xny0 − x0yn //firstPoint and last point
twoPointPairs is a list of sequence of pairs ie List[Seq[(Int, Int)]] from 1st point until last point. For first and last point part of shoelace formula will have to be calculated separately.
*/
val (x1, y1) = p1
val (x2, y2) = p2
(x1 * y2 - x2 * y1 )
}
def main(args: Array[String]): Unit = {
val stdin = scala.io.StdIn
val n = stdin.readLine.trim.toInt
val points: Seq[(Int, Int)] = for (nItr <- 1 to n) yield { //points = Seq(p1, p2, ... ,pn) = Seq((x1, y1), (x2, y2), ... ,(xn, yn))
val readline = stdin.readLine.split(" ").map(x => x.toInt) //split returns an array of string, map converts array of string to array of int
val xCoordinate = readline(0) //accessing 0th element of array x
val yCoordinate = readline(1)
(xCoordinate, yCoordinate)
}
val twoPointPairs: List[Seq[(Int, Int)]] = points.sliding(2).toList // p2p3pairs: List[Seq[(Int, Int)]] every Seq here has 2 elements ie List( Seq( (x1, y1), (x2, y2) ), Seq( (x2, y2), (x3, y3) ) ,... , Seq( (xn-1, yn-1), (xn, yn) ) )
val areaOfPolygon = 0.5 * (twoPointPairs.map {
case Seq(p1, p2) => partOfShoelaceFormula(p1, p2)
}.sum + partOfShoelaceFormula(points.last, points.head)) //here (lastPoint, firstPoint) should be the order
println(areaOfPolygon)
}
}
println(areaOfPolygon)
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Compute the Area of a Polygon
You are viewing a single comment's thread. Return to all comments →
/* scala -
to calculate the area of a polygon when its coordinates are given we ll use shoelace formula = 0.5 * ( x1y2 − x2y1 + x2y3 − x3y2 +. . . + xny0 − x0yn)
(x1,y1), (x2,y2) => x1y2 − x2y1 (x2,y2), (x3,y3) => x2y3 − x3y2 . . . (xn,yn), (x0,y0)=> xny0 − x0yn //firstPoint and last point
twoPointPairs is a list of sequence of pairs ie List[Seq[(Int, Int)]] from 1st point until last point. For first and last point part of shoelace formula will have to be calculated separately. */
object ComputeTheAreaOfAPolygon {
def partOfShoelaceFormula(p1: (Int, Int), p2: (Int, Int)): Double = {
}
def main(args: Array[String]): Unit = { val stdin = scala.io.StdIn
} }
} }