Last active
March 3, 2021 16:46
-
-
Save chansey97/3f1090b14e3d3359f52abaaa9ca0778c to your computer and use it in GitHub Desktop.
Solve PCP by BFS.
This file contains 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 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")] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related tweets
https://twitter.com/chansey97/status/1262797584818556930