gpt4 book ai didi

algorithm - 如何为字符串列表编写 Haskell BFS 算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:57:58 26 4
gpt4 key购买 nike

<分区>

我尝试使用 Haskell 解决“梯子”问题。任务是在相同长度的两个单词之间的单词列表中找到最短路径(如果存在)。单词连接的规则是

  1. 我们可以用一个替换(word -> cord)从另一个词中获取一个词
  2. 这个词(在我的例子中是“cord”)应该在我们的词表中

因此,如果我们有列表[word, cord, wore] 并且我们需要一个从 wore 到 cord 的阶梯,答案将是 wear -> word -> cord。我尝试使用 bfs 算法来解决这个问题。为了获得单词的邻居,我使用下一个函数

--(x:xs) - letters
getChanged :: [String] -> [Char] -> [String] -> [String]
getChanged cont (x:xs) ans =
if length xs == 0
then ans ++ [cont !! 0 ++ [x] ++ cont !! 1]
else getChanged cont xs (ans ++ [cont !! 0 ++ [x] ++ cont !! 1])

--get for getChanged
divide :: String -> Int -> [String]
divide word index = [(take index word)] ++ [(drop (index + 1) word)]


--word alphabet indexToChange AnswerAcc Answer
getNeighbours :: String -> [Char] -> Int -> [String] -> [String]
getNeighbours word alphabet index answerAcc =
if index == length word
then
answerAcc
else
getNeighbours word alphabet (index + 1) (answerAcc ++ (getChanged (divide word index) alphabet []))

main = do
putStrLn (unlines (getNeighbours "hello kitty" ['a', 'b', 'c'] 0 []))

梯子签名是这样的

ladder :: String -> String -> String -> IO()
ladder word1 word2 words = do
content <- readFile words
let words = lines content
let myWords = Set.fromList (filter (\x -> length x == length word1) words)
if not (Set.member word1 myWords) || not (Set.member word2 myWords)
then error "Path not found"
else do
let b = ["1"]
putStrLn $ unlines b
print $ length b

我尝试使用 HashSet 和 HashMap 但一无所获。现在我坚持这一点。我的问题是这个问题怎么写bfs?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com