我有一个字母unscrambler的工作代码。但我想提高产量。我希望有人可以帮我解决这个问题。
当我输入单词" TEST"时,它将输出以下内容:
Eses Sees Sets Sett Stet Tees Test Tets
如何在结果中不允许重复字母?不应包括" Sees和T恤这个词。
继承我正在使用的代码。
function GetScrabbleWords($targetWord)
{
$targetArray=str_split($targetWord);
$wordFileArray=array(3=>'data/threeletters.txt',4=>'data/fourletters.txt',5=>'data/fiveletters.txt',6=>'data/sixletters.txt',7=>'data/sevenletters.txt');
foreach($wordFileArray as $fileWordLength=>$wordFile)
{
$wordFile=file($wordFile);
sort($wordFile);
foreach($wordFile as $word)
{
$word=trim($word);
$wordArray=str_split($word);
$diffArray=array_diff($wordArray,$targetArray);
if (count($diffArray)==0) $scrabbleArray[$fileWordLength][$word]=$word;
}
}
if ( !empty($scrabbleArray)) {
unset($scrabbleArray[7][$targetWord]);
return $scrabbleArray;
}
}
$target=Input::get('formvar');
$targetWord=Str::upper($target);
$my_values = array(GetScrabbleWords($targetWord));
echo $my_values;
答案 0 :(得分:0)
以下是PHP Cookbook中Finding All Permutations of an Array函数的修改版本。我希望这是你正在寻找的东西,!preg_match( '/(\w)\1+/', $perms )
是检查排列中多个重复字母的部分。
function pc_permute( $items, $perms = array( ), &$result = array() ) {
if ( empty( $items ) ) {
$perms = implode( $perms );
if ( !in_array( $perms, $result ) && !preg_match( '/(\w)\1+/', $perms ) ) $result[] = $perms;
} else {
for ( $i = count($items) - 1; $i >= 0; --$i ) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice( $newitems, $i, 1 );
array_unshift($newperms, $foo);
pc_permute( $newitems, $newperms, $result );
}
}
return $result;
}
$result = pc_permute( str_split( 'test' ) );
/*
Array
(
[0] => test
[1] => etst
[2] => tset
[3] => stet
[4] => tets
[5] => tste
)
*/