Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Calculate a length of a line between each pair of following points p
, defined with x
and y
coordinate:
(p0, p1), (p1, p2), ..., (pn-1, p0)
Length of a line between two points:
$$l = \sqrt{{(x_1 – x_2)}^2 + {(y_1 – y_2)}^2}$$
Make sum of the lengths.
I created solution in:
All solutions are also available on my GitHub.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import scala.io.Source object ComputePolygonPerimeter extends App { val lines = Source.stdin.getLines().toList val n = lines.head.toInt val pairs = lines.tail.map(_.split(" ").map(_.toInt)).map(array => Tuple2(array(0), array(1))) println(perimeter(pairs)) def perimeter(points: List[(Int, Int)]) = { val n = points.length (0 until n).map(i => length(pairs(i % n), pairs((i + 1) % n))).sum } def length(p1: (Int, Int), p2: (Int, Int)) = { Math.sqrt((Math.pow(p2._1 - p1._1, 2)) + (Math.pow(p2._2 - p1._2, 2))) } } |