From 375bdba185413f0d02cb3a98f2fbbe6a378eadac Mon Sep 17 00:00:00 2001 From: Victor Martinez <49537445+JasterV@users.noreply.github.com> Date: Tue, 18 Mar 2025 13:40:26 +0100 Subject: [PATCH] implement ladder graph creation --- ladder.cabal | 1 + src/Ladder.hs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 src/Ladder.hs diff --git a/ladder.cabal b/ladder.cabal index 2c5aea4..290057c 100644 --- a/ladder.cabal +++ b/ladder.cabal @@ -27,6 +27,7 @@ library exposed-modules: Data.AssocMap Graph + Ladder Lib PermutationMap other-modules: diff --git a/src/Ladder.hs b/src/Ladder.hs new file mode 100644 index 0000000..80d4fed --- /dev/null +++ b/src/Ladder.hs @@ -0,0 +1,34 @@ +module Ladder (readDictionary, mkLadderGraph) where + +import Data.Char (isLower) +import qualified Data.List as L +import qualified Graph as G +import qualified PermutationMap as PM +import Prelude hiding (lines, words) + +type Dictionary = [String] + +readDictionary :: String -> IO Dictionary +readDictionary filename = do + text <- readFile filename + let lines = L.lines text + let lowercaseWords = map (filter isLower) lines + return (L.nub lowercaseWords) + +mkLadderGraph :: Dictionary -> G.DiGraph String +mkLadderGraph dict = G.buildDiGraph [(word, computeCandidates permMap word) | word <- dict] + where + permMap = PM.createPermutationMap dict + +computeCandidates :: PM.PermutationMap -> String -> [String] +computeCandidates permMap word = + -- Delete the original word from the permutations list + L.delete word permutations + where + removed = [L.delete c word | c <- word] + added = [c : word | c <- ['a' .. 'z']] + modified = [x : L.delete y word | x <- ['a' .. 'z'], y <- word, x /= y] + -- Sort and deduplicate all the candidates + candidates = L.nub $ map L.sort (added ++ removed ++ modified ++ [word]) + -- For each candidate, lookup all its permutations + permutations = L.concatMap (\w -> PM.findWithDefault [] w permMap) candidates