再帰クエリで問題が発生しています。レキシコンを検索し、スクラブルワードファインダーのように、特定の文字セットで作成できる単語を返すphpスクリプトを作成しようとしています。優れた解決策を持つスレッドが他にもあることは知っていますが、そこで問題の解決策を見つけることができませんでした。関数は再帰的に継続するため、文字が複数重複している単語を検索します。たとえば、最初に文字a、d、およびtを使用して関数を呼び出すと、関数は2つの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()