要查找所有可能的有效字这是下面的步骤
- 找到所有可能的组合
- 查找每个排列的组合中的每个字
- 搜索数据库的话
- 列表中字
脚本
个
$tiles = array("A", "B", "C", "T", "E", "E") ;
$words = array();
$set = powerSet($tiles,2);
$mysql = new mysqli("localhost","root","","word");
$sql = "SELECT id from dic WHERE word = '%s'" ;
foreach ($set as $key => $value)
{
$word = implode("", $value);
$wordPermutation = permute($word);
foreach($wordPermutation as $keyWord)
{
if(!in_array($keyWord, $words))
{
//if($result = $mysql->query(sprintf($sql,$keyWord)))
//{
//var_dump(sprintf($sql,$keyWord));
//if($result->num_rows > 0)
//{
$words[] = $keyWord ;
//}
//}
}
}
}
print_r($words);
功能
function powerSet($in, $minLength = 1, $max = 10) {
$count = count ($in);
$members = pow (2, $count);
$return = array();
for($i = 0; $i < $members; $i ++) {
$b = sprintf ("%0" . $count . "b", $i);
$out = array();
for($j = 0; $j < $count; $j ++) {
if ($b {$j} == '1')
$out [] = $in [$j];
}
if (count ($out) >= $minLength && count ($out) <= $max) {
$return [] = $out;
}
}
return $return;
}
function permute($str) {
if (strlen($str) < 2) {
return array($str);
}
$permutations = array();
$tail = substr($str, 1);
foreach (permute($tail) as $permutation) {
$length = strlen($permutation);
for ($i = 0; $i <= $length; $i++) {
$permutations[] = substr($permutation, 0, $i) . $str[0] . substr($permutation, $i);
}
}
return $permutations;
}
请注意,我commented
从数据库验证部分,使演示可以工作
观看演示
http://codepad.viper-7.com/oG6E6w
的可能重复(http://stackoverflow.com/questions/ 880559 /算法对获得-A-列表中,所有的词 - 这 - 是 - 字谜 - 的 - 所有子-scrabb)。另请参阅http://stackoverflow.com/questions/tagged/scrabble – JJJ 2012-04-21 13:21:47
那么最简单的算法(但也是最没有效率的)就是简单地检查所有可能的组合并查询数据库。我也很想知道这里会发生什么。 – 2012-04-21 13:22:10