Created
July 23, 2016 05:53
-
-
Save rhaseven7h/4f19eb27a9cf7477f8a2db1b105ee9da to your computer and use it in GitHub Desktop.
HackerRank.com - Functional Programming - Functions or Not? - Haskell
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
import qualified Data.Map.Strict as MS | |
import Data.List | |
-- Basically a valid function is that which | |
-- always return the same output for a given input, | |
-- that is, a function that one time returns 3 for f(1) | |
-- and the next returns 5 for the same f(1) is NOT | |
-- a valid function | |
-- | |
-- This algorithm checks we have unique outputs for | |
-- unique inputs, if more than one non-unique return | |
-- is found for a given input, the function is invalid. | |
insertInMap :: (Ord a) => MS.Map a [a] -> [a] -> MS.Map a [a] | |
insertInMap m e | |
| MS.member nk m = MS.insert nk (nub (nv : cv)) rm | |
| otherwise = MS.insert nk [nv] m | |
where nk = head e | |
nv = last e | |
cv = m MS.! nk | |
rm = MS.delete nk m | |
getMapping m = foldl (\m e -> insertInMap m e) MS.empty m | |
isValidFunc m = nonUniqueLen == 0 | |
where mapping = getMapping m | |
nonUnique = filter (\e -> length e > 1) (MS.elems mapping) | |
nonUniqueLen = length nonUnique | |
mapToInts lns = map (\s -> map (\ss -> read ss :: Int) (words s)) lns | |
caseDefs c [] = reverse c | |
caseDefs c l = caseDefs (tc : c) rst | |
where tcc = read (head l) :: Int | |
tc = mapToInts $ take tcc (tail l) | |
rst = drop (tcc + 1) l | |
main = do | |
raw <- getContents -- readFile "input.txt" | |
let lns = tail $ lines raw | |
defs = caseDefs [] lns | |
res = map isValidFunc defs | |
isYesOrNo = map (\b -> if b then "YES" else "NO") res | |
mapM_ putStrLn isYesOrNo | |
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
3 | |
3 | |
1 1 | |
2 2 | |
3 3 | |
4 | |
1 2 | |
2 4 | |
3 6 | |
4 8 | |
3 | |
1 2 | |
2 4 | |
3 6 | |
2 9 | |
4 9 |
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
YES | |
YES | |
NO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment