Advertisement
Guest User

Untitled

a guest
May 24th, 2012
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Control.Monad
  2. import Control.Applicative
  3.  
  4. main = do
  5.     [_, numWords, numCases] <- fmap ((map read) . words) $ getLine :: IO [Int]
  6.     (known, rest) <- fmap ((splitAt numWords) . lines) $ getContents
  7.     forM_ [1..numCases] (\caseNum -> do
  8.         let possibleWords word = filter (`elem` known) (permuteWord word)
  9.             allPossibles = map possibleWords rest
  10.         putStrLn $ "Case #" ++ show caseNum ++ ": " ++ show (length $ allPossibles !! (caseNum - 1))
  11.         )
  12.  
  13. -- I COULD HAVE JUST REPLACED THE PARENTHESES WITH BRACKETS
  14. -- AND TREATED THEM AS REGULAR EXPRESSIONS
  15. permuteWord :: String -> [String]
  16. permuteWord [] = []
  17. permuteWord word | '(' `notElem` word = [word]
  18.                  | otherwise = let (first, _:rest) = break (== '(') word
  19.                                    (group, _:rest') = break (== ')') rest
  20.                               in [((first ++ [a]) ++) | a <- group] <+> (permuteWord rest')
  21.  
  22. -- This was just a quick fix to make [f] <*> [] return [f []] instead of []
  23. --      (e.g. [("hi"++), ("there"++)] <+> [] == ["hi", "there"])
  24. (<+>) :: [[a] -> b] -> [[a]] -> [b]
  25. []     <+> _  = []
  26. (f:fs) <+> [] = (f []) : fs <+> []
  27. fs     <+> x  =  fs <*> x
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement