Compute the Area of a Polygon – HackerRank Solution

In this post, we will solve Compute the Area of a Polygon HackerRank Solution. This problem (Compute the Area of a Polygon) is a part of HackerRank Functional Programming series.

Task

You are given the cartesian coordinates of a set of points in a 2D plane. When traversed sequentially, these points form a Polygon, P, which is not self-intersecting in nature. Can you compute the area of polygon P?

Input Format

The first line contains an integer, N, denoting the number of points.
The N subsequent lines each contain 2 space-separated integers denoting the respective x and y coordinates of a point.

Constraints

  • No 2 points are coincident, and polygon P is obtained by traversing the points in a counter-clockwise direction.
  • 4 <= N <= 1000
  • 0 <= x, y <= 1000

Output Format

For each test case, print the area of P (correct to a scale of one decimal place).

Note: Do not add any leading/trailing spaces or units; it is assumed that your result is in square units.

Sample Input

4
0 0
0 1  
1 1  
1 0

Sample Output

1

Explanation

The given polygon is a square, and each of its sides are 1 unit in length.
area(P) = length x width = 1 x 1 = 1, so we print  on a new line.

Solution – Compute the Area of a Polygon – HackerRank Solution

Scala

import java.util.Scanner

object Solution {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt

    case class Coord(x: Double, y: Double)

    val coords = (0 until n).map(_ => Coord(sc.nextInt, sc.nextInt))

    val square = math.abs((coords.last +: coords).sliding(2)
      .map(list => (list.head, list.last))
      .map { case (c0, c1) => c0.x * c1.y - c0.y * c1.x }
      .sum / 2)

    println(square)
  }
}

Note: This problem (Compute the Area of a Polygon) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *