Created
May 23, 2015 19:12
-
-
Save tefimov/d7201a98ef249d3d5165 to your computer and use it in GitHub Desktop.
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 | |
| import System.IO | |
| import qualified Data.Set as Set | |
| import Queue | |
| main = do | |
| text <- readFile "wordsShort.txt" | |
| let words = Set.fromList $ lines text | |
| w1 <- getLine | |
| w2 <- getLine | |
| putStr $ unlines $ ladder words w1 w2 | |
| ladder :: Set.Set String -> String -> String -> [String] | |
| ladder words w1 w2 = reverse $ ladder' (Queue [[w1]] []) (Set.insert w2 words) w2 | |
| ladder' :: Queue [String] -> Set.Set String -> String -> [String] | |
| ladder' (Queue [] []) _ _ = error "No way" | |
| ladder' q words w2 | |
| |cw == w2 = path | |
| |otherwise = ladder' q' words' w2 | |
| where path = fst $ dequeue q | |
| cw = head $ path | |
| n_words = Set.filter (\w -> distance w cw == 1) words | |
| n_paths = Set.map (\x -> (x:path)) n_words | |
| words' = Set.difference words n_words | |
| q' = enqueueList (Set.toList n_paths) (snd (dequeue q)) | |
| distance :: String -> String -> Int | |
| distance w1 w2 | |
| |difflen < 0 = distance w2 w1 | |
| |otherwise = diffchars_s + difflen | |
| where difflen = length w1 - length w2 | |
| diffchars_s = minimum [length (diffchars s) | s <- [0..difflen]] | |
| where diffchars s = [i | i <- [0..(length w2 - 1)], (w1 !! (i + s)) /= (w2 !! i)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment