2

我遇到了递归查询的问题。我正在尝试创建一个 php 脚本,该脚本将搜索词典并返回可以使用给定字母集组成的单词,例如拼字游戏单词查找器。我知道还有其他具有很好解决方案的线程,但是我在那里找不到解决我的问题的方法。随着函数递归地继续,它正在查找具有多个字母重复的单词。例如,如果我最初使用字母 a、d 和 t 调用该函数,该函数将返回包含两个 A 的单词“data”。我认为我的代码的底部应该通过从数组中删除一个用过的字母来防止这种情况,但我错过了一些东西。我应该注意,我是一个新手,目前在学校,但这不是任何类型的学校项目,我只是想自己学习一些东西。提前致谢。

    // $wordsArray is the array pf possible words so far
    // $lettersArray is the array of remaining letters
    // $position is the current search position of the words
    // $solvedWords is an array containing all of the solved words
    function search($wordsArray, $lettersArray, $position, $solvedWords) {
        // if there are letters in the letters array continue
        if (count($lettersArray) > 0) {
            $foundWords = array();// foundWords is an array containing possible words given the current letter searched
            // for each remaining letter, check each word for a match at the next position
            foreach ($lettersArray AS $letter) {
                foreach ($wordsArray AS $word) {
                    // if there is a match with the current letter at the current search position, check to see if it is a complete word
                    if (substr($word, $position, 1) == $letter) {
                        if (strlen($word) == ($position+1)) {
                            array_push($solvedWords, $word); // if complete, add to the solved words
                        } else {
                            array_push($foundWords, $word); // if not a complete word, add to the foundWords array of possible words
                        } // end if
                    } // end if
                } // end foreach

                // $remainingLetters array should be the same as the letters array but removed the current letter at this position
                $remainingLetters = $lettersArray;
                $done = false;
                // if there is a letter match, remove the letter from the remainingLetters array
                for ($i = 0; $i < count($remainingLetters); $i++) {
                    if (!$done) {
                        if ($letter == $remainingLetters [$i]) {
                            unset ($remainingLetters [$i]);
                            $remainingLetters = array_values($remainingLetters);
                            $done = true;
                        } // end if
                    } // end if
                } // end foreach
                if ($remainingLetters)
                    $solvedWords = search($foundWords, $remainingLetters, ($position+1), $solvedWords);
            } // end foreach
            return $solvedWords;
        } // end if

    } // end search()
4

1 回答 1

0

-已解决-我通过为每个字母初始化 $foundWords 数组一次解决了这个问题,而不是为函数初始化一次。我认为它在从函数调用底部的数组中删除字母之前保存了先前的搜索。

于 2012-12-02T02:30:44.163 回答