【发布时间】:2012-12-02 01:51:23
【问题描述】:
我遇到了递归查询的问题。我正在尝试创建一个 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()
【问题讨论】:
-
如果没有彻底阅读和测试你的代码,我认为你应该使用
foreach在底部循环remainingLetters,和/或使用array_slice来制作一个数组的副本不包含给定索引 (php.net/manual/en/function.array-slice.php) 而不是unseting 数组索引。如果你unset一个数组索引然后根据索引计数循环它,你最终可能会尝试访问未设置的值。 -
感谢 taz 的建议,我将实施。我还通过为每个字母初始化一次 $foundWords 数组来解决这个问题,而不是为函数初始化一次。我认为它在从函数调用底部的数组中删除字母之前保存了先前的搜索。