Skip to content

Instantly share code, notes, and snippets.

@tefimov
Created May 23, 2015 19:12
Show Gist options
  • Select an option

  • Save tefimov/d7201a98ef249d3d5165 to your computer and use it in GitHub Desktop.

Select an option

Save tefimov/d7201a98ef249d3d5165 to your computer and use it in GitHub Desktop.
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