Skip to content

Instantly share code, notes, and snippets.

@rhaseven7h
Created July 20, 2016 22:39
Show Gist options
  • Save rhaseven7h/e231e1ec7b993a92ccd5c05975a7de02 to your computer and use it in GitHub Desktop.
Save rhaseven7h/e231e1ec7b993a92ccd5c05975a7de02 to your computer and use it in GitHub Desktop.
HackerRank Calculate Perimeter - Functional Programming - Ad hoc
-- Calculate the perimeter delineated by the list of points
--
-- Input from standard in is as follows:
--
-- 4
-- 0 0
-- 0 1
-- 1 1
-- 1 0
--
-- First line is the number of points that follow
--
-- Output is as follows:
--
-- 4.0
--
-- That is, the calculation of the perimeter described by the input
--
import Control.Monad
import System.IO
distance :: (Floating a) => (a, a) -> (a, a) -> a
distance (ax, ay) (bx, by) = sqrt (((bx - ax) ** 2) + ((by - ay) ** 2))
perimeter [] = -1
perimeter [i] = 0
perimeter [a, b] = distance a b
perimeter (ah:at) = distance ah (head at) + perimeter at
main = do
input <- getLine
inputs <- replicateM (read input) getLine
let dataset = map (\x -> map (\w -> read w :: Int) (words x)) inputs
let points = map (\x -> (fromIntegral (head x), fromIntegral (last x))) dataset
let polygon = points ++ [ head points ]
print $ perimeter polygon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment