I am having an issue with a recursive query. I am trying to create a php script that will search a lexicon and return words that can be made with a given set of letters, like a scrabble word finder. I know there are other threads with great solutions, but I couldn’t find a solution to my issue there. As the function continues recursively, it is finding words with multiple duplicates of a letter. For example, if I initially call the function with the letters a, d, and t, the function will return the word ‘data’, which has two A’s. I thought the bottom segment of my code should prevent that by removing a used letter from the array, but I am missing something. I should note that I am a novice, currently in school, but this is not for a school project of any kind, I am just trying to learn something on my own. Thanks in advance.
// $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()
-Solved-
I solved the issue by initializing the $foundWords array once for each letter, and not once for the function. I think it was saving prior searches before it was removing the letter from the array at the bottom of the function call.