Skip to main content
4 of 7
Rollback to Revision 2

How to write functions which can find words with specified letters

I have sample function which can search words from dictionary with input specified words:

Function code:

function getWordsWithOnlySpecifedLetters(array $dictionary, string $letters)
{
    foreach ($dictionary as $key => $value) {
        if(mb_strlen($value) > mb_strlen($letters)) unset($dictionary[$key]);
    }

    $step = 0;
    $strSplit = preg_split('//u', $letters, null, PREG_SPLIT_NO_EMPTY);
    $result = [];
    foreach ($dictionary as $word) {
        $step++;
        $wordSplit = preg_split('//u', $word, null, PREG_SPLIT_NO_EMPTY);
        sort($wordSplit);
        sort($strSplit);
        if (array_map('mb_strtolower', $wordSplit) === array_map('mb_strtolower', $strSplit)) {
            //echo "All specified letters from $letters are in $word | Step $step<hr>" . PHP_EOL;
            $result[] = $word;
        }
    }

    return $result;
}

Example usage:

$dictionary = ['apple', 'sample', 'api', 'pia', 'тоҷик'];
getWordsWithOnlySpecifedLetters($dictionary, "aip");

Return: api, pia

getWordsWithOnlySpecifedLetters($dictionary, "leamps");

Return: sample


**Second function code:**
function getWordsWithSpecifedLetters(array $dictionary, string $letters)
{
    $step = 0;
    mb_internal_encoding("UTF-8");
    $result = [];
    foreach ($dictionary as $word) {
        $step++;
        $wordSplit = preg_split('//u', $word, null, PREG_SPLIT_NO_EMPTY);
        $strSplit = preg_split('//u', $letters, null, PREG_SPLIT_NO_EMPTY);
        $wordSplit = array_filter($wordSplit, function($x) use (&$strSplit) {
            if (in_array(strtolower($x), array_map('strtolower', $strSplit), true)) {
                $pos = array_search(strtolower($x), array_map('strtolower', $strSplit), true);
                unset($strSplit[$pos]);
                return false;
            }
            return true;
        });
        if (count(array_diff($strSplit,$wordSplit)) === 0) {
            //echo "$word contains all letters of $letters | Step $step<hr>" . PHP_EOL;
            $result[] = $word;
        }
    }

    return $result;
}

This function can search word with specified letters and other letters.

Example usage:

$dictionary = ['apple', 'sample', 'api', 'pia', 'тоҷик'];
getWordsWithSpecifedLetters($dictionary, "ple");

Return: sample, apple

I have more 90000 words in my dictionary (utf-8). Functions work very slow. For example from 90000 words found words on 50000 or 60000 loop. Can be performed this functions?