Created
February 14, 2012 08:24
-
-
Save ijt/1824798 to your computer and use it in GitHub Desktop.
Print the median of a newline-separated list of numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env runhaskell | |
import Data.List (sort, (\\)) | |
import Test.QuickCheck (Property, (==>)) | |
main = interact (showLn . median . map read . lines) | |
showLn :: Show a => a -> String | |
showLn x = show x ++ "\n" | |
median :: [Float] -> Float | |
median xs | odd (length xs) = sort xs !! (length xs `div` 2) | |
| otherwise = 0.5 * (sorted !! i + sorted !! (i + 1)) | |
where sorted = sort xs | |
i = (length xs `div` 2) - 1 | |
-- The median of a list of repeated x is just x. | |
prop_sameNumber :: Int -> Float -> Property | |
prop_sameNumber n x = n > 0 && n < 100 ==> median (replicate n x) == x | |
-- The median of [-n..n] is 0 for any n. | |
-- This exercises the odd length case. | |
prop_increasing :: Int -> Property | |
prop_increasing n = n >= 0 && n < 100 ==> median (map fromIntegral [-n..n]) == 0.0 | |
-- The median of [-n..n] with 0 removed is 0 for any n. | |
-- This exercises the even length case. | |
prop_increasing2 :: Int -> Property | |
prop_increasing2 n = n > 0 && n < 100 ==> median (map fromIntegral ([-n..n] \\ [0])) == 0.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment