有递归功能的麻烦

时间:2012-12-02 01:51:24

标签: php recursion

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

    // $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()

1 个答案:

答案 0 :(得分:0)

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