In this post, we will solve Compute the Perimeter of a Polygon HackerRank Solution. This problem (Compute the Perimeter of a Polygon) is a part of HackerRank Functional Programming series.
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 perimeter of polygon P?
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.
- No 2 points are coincident, and polygon P is obtained by traversing the points in a clockwise direction.
- 3 <= N <= 1000
- 0 <= x, y <= 1000
For each test case, print the perimeter of P (correct to a scale of one decimal place).
Note: Do not add any leading/trailing spaces or units.
4 0 0 0 1 1 1 1 0
The given polygon is a square, and each of its sides are 1 unit in length. perimeter(P) = 1 + 1 + 1 + 1 = 4, so we print 4 on a new line.
Solution – Compute the Perimeter of a Polygon – HackerRank Solution
d [x,y,x1,y1] = sqrt $ (x1 - x)^2 + (y1 - y)^2 d _ = 0 p  acc = acc p points acc = p (drop 2 points) (acc + (d (take 4 points))) perimeter points = p (points ++ (take 2 points)) 0 main :: IO () main = do _ <- getLine x <- getContents let f = map read $ words x print $ perimeter f