【发布时间】:2021-02-16 19:23:34
【问题描述】:
让我解释一下,我需要这个来根据一组预定义的单词开发一个独特的标题生成器。
例如,我有这个单词列表:
$list = ['苹果', '香蕉', '梨'];
我对标题的大小有限制,例如:1 个字符 如果我生成所有排列的列表,我将拥有:
apple
banana
pear
apple banana
apple pear
apple banana pear
banana apple
banana pear
banana apple pear
pear apple
pear banana
pear banana apple
但我不想要这个,任何规则是:单词不能在另一组单词中再次重复,我只想要最大的一组单词
结果是:
apple banana
apple pear
banana pear
我已经尝试了以下解决方案,但这些都没有帮助:
PHP algorithm to generate all combinations of a specific size from a single set
Every (specific sized) combination from set/array with no duplicate items
Efficient PHP algorithm to generate all combinations / permutations of inputs
How do you generate a list of all possible strings given a generator of characters and a length?
我有这段代码,但它没有按我的意愿删除重复项
public static function search_get_combos($array = array(), $maxCaracters=12) {
sort($array);
$terms = array();
for ($dec = 1; $dec < pow(2, count($array)); $dec++) {
$curterm = array();
foreach (str_split(strrev(decbin($dec))) as $i => $bit) {
if ($bit) {
$curterm[] = $array[$i];
}
}
if (!in_array($curterm, $terms) && count($curterm) > 1) {
$title = implode(' ', $curterm);
if (strlen($title) <= $maxCaracters){
$terms[$title] = $curterm;
}
}
}
return $terms;
}
输出:
array(6) {
["Apple"]=>
array(1) {
[0]=>
string(5) "Apple"
}
["Banana"]=>
array(1) {
[0]=>
string(6) "Banana"
}
["Apple Banana"]=>
array(2) {
[0]=>
string(5) "Apple"
[1]=>
string(6) "Banana"
}
["Pear"]=>
array(1) {
[0]=>
string(4) "Pear"
}
["Apple Pear"]=>
array(2) {
[0]=>
string(5) "Apple"
[1]=>
string(4) "Pear"
}
["Banana Pear"]=>
array(2) {
[0]=>
string(6) "Banana"
[1]=>
string(4) "Pear"
}
}
【问题讨论】:
-
您说“我只想要最大的一组词
-
对,说错了^^
标签: php permutation