Skip to content

Instantly share code, notes, and snippets.

@Shamrock-Frost
Created November 17, 2016 16:27
Show Gist options
  • Select an option

  • Save Shamrock-Frost/97a0772a89768923b107e0756961f419 to your computer and use it in GitHub Desktop.

Select an option

Save Shamrock-Frost/97a0772a89768923b107e0756961f419 to your computer and use it in GitHub Desktop.
Hackerrank solution
{-# LANGUAGE ConstraintKinds, DeriveFunctor #-}
import Text.Printf (printf)
import Data.Foldable (fold)
import Data.Bifunctor (bimap)
import Data.Monoid ((<>))
type PolynomialAble pow num = (Integral pow, Floating num)
data Monomial pow = Ln | ToThe pow deriving (Functor, Eq, Show)
newtype Polynomial pow num = P { getTerms :: [(Monomial pow, num)] } deriving (Eq, Show)
sqrPoly :: PolynomialAble pow num => Polynomial pow num -> Polynomial pow num
sqrPoly (P p) = P $ concatMap (\(ToThe k, v) -> bimap (fmap (+ k)) (* v) `map` p) p
toFn :: PolynomialAble pow num => Polynomial pow num -> (num -> num)
toFn = foldr (\(n, c) fn -> \y -> let f = case n of { ToThe n' -> (^^ n'); Ln -> log } in fn y + c * f y) (const 0) . getTerms
solve :: Double -> Double -> Polynomial Int Double -> (Double, Double)
solve l r p = (area, volume)
where area = integrate p l r
volume = pi * integrate (sqrPoly p) l r
main :: IO ()
main = getContents >>= putStrLn . uncurry (cojoin $ printf "%.1f\n") . (\(a:b:(l:r:_):_) -> solve l r . P $ zip (map (ToThe . floor) b) a) . map (map read . words) . lines
where cojoin f = \x x' -> f x <> f x'
integrate :: PolynomialAble pow num => Polynomial pow num -> num -> num -> num
integrate coefs lbound rbound = capF rbound - capF lbound
where capF = toFn $ reversePowerRule coefs
reversePowerRule :: PolynomialAble pow num => Polynomial pow num -> Polynomial pow num
reversePowerRule = P . map (uncurry aux) . getTerms
aux (ToThe idx) c
| idx == -1 = (Ln,c)
| otherwise = let idx' = idx + 1 in (ToThe idx', c / fromIntegral idx')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment