Skip to content

Instantly share code, notes, and snippets.

@chansey97
Last active March 3, 2021 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chansey97/3f1090b14e3d3359f52abaaa9ca0778c to your computer and use it in GitHub Desktop.
Save chansey97/3f1090b14e3d3359f52abaaa9ca0778c to your computer and use it in GitHub Desktop.
Solve PCP by BFS.
module PCP where
import Data.List
import Data.Tree
-- breadth-first traversal
levelf :: Forest a -> [[a]]
levelf = unfoldr f
where f [] = Nothing
f xs = Just (map rootLabel xs, concat $ map subForest xs)
bftf :: Forest a -> [a]
bftf = concat . levelf
-- PCP
type Domino = (String, String)
type DominoDB = [Domino]
type DominoPath = [Domino]
buildForestFrom :: [(DominoPath, DominoDB)] -> Forest DominoPath
buildForestFrom = unfoldForest (\(path, db) -> (path, map (\x -> (path ++ [x], db)) db))
buildForest :: DominoDB -> Forest DominoPath
buildForest db = buildForestFrom $ map (\x -> ([x], db)) db
solve :: Int -> DominoDB -> DominoPath
solve n = head . filter p . take n . bftf . buildForest
where p path = let (xs, ys) = unzip path
in concat xs == concat ys
main = do print $ solve 10000 [("b", "ca"),
("a", "ab"),
("ca", "a"),
("abc", "c")]
--λ> main
--[("a","ab"),("b","ca"),("ca","a"),("a","ab"),("abc","c")]
@chansey97
Copy link
Author

chansey97 commented May 26, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment