Last active
June 20, 2017 04:21
-
-
Save ptvirgo/18b4a17b4a41e57298b0135e38097276 to your computer and use it in GitHub Desktop.
Attempting Knuth-Morris-Pratt in Haskell for Hackerrank. But - time out ?
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
module Main where | |
-- | Return a Knuth-Morris-Pratt index for a given string | |
stringIndex :: String -> [Int] | |
stringIndex "" = [] | |
stringIndex txt = indexr [0] 0 1 where | |
indexr :: [Int] -> Int -> Int -> [Int] | |
indexr rsf subPos chrPos | |
| length rsf == length txt = rsf | |
| txt !! subPos == txt !! chrPos | |
= indexr (rsf ++ [subPos + 1]) (subPos + 1) (chrPos + 1) | |
| subPos > 1 = indexr rsf (rsf !! (subPos - 1)) chrPos | |
| otherwise = indexr (rsf ++ [0]) 0 (chrPos + 1) | |
-- | Tells us if given text contains given string. Relies on isSubstring for | |
-- | recursive searching. | |
stringHaz :: String -> String -> Bool | |
stringHaz text term = isSubstring 0 0 where | |
termTable = stringIndex term | |
jump 0 = 1 | |
jump distance = 1 + (termTable !! distance) | |
resume 0 = 0 | |
resume distance = max (distance - (jump distance)) 0 | |
isSubstring :: Int -> Int -> Bool | |
isSubstring textPos termPos | |
| length term <= termPos = True | |
| length text <= textPos - 1 + length term = False | |
| term !! termPos == text !! (textPos + termPos) = isSubstring textPos (termPos + 1) | |
| otherwise = isSubstring (textPos + (jump termPos)) (resume termPos) | |
answer :: Bool -> String | |
answer True = "YES" | |
answer False = "NO" | |
stuplefy :: IO (String, String) | |
stuplefy = do | |
a <- getLine | |
b <- getLine | |
return (a, b) | |
main = do | |
init <- getLine | |
let reps = read init :: Int | |
hackerrankTests <- sequence $ replicate reps stuplefy | |
let results = map (answer . (\cs -> stringHaz (fst cs) (snd cs))) hackerrankTests | |
let output = foldl (\rsf x -> rsf ++ "\n" ++ x) (head results) (tail results) | |
putStrLn output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment