PHP-php求一个高效的组合算法

a
b
..
a,b
a,c
a,d
...
a,b,c
a,b,c,d
......

评论（4）

2017-10-16 4 楼

2017-10-15 3 楼

<?php
\$total_number=64+32+16+8+4+2+1;

print_combination(\$total_number);

//位运算函数
function bit_operation(\$input)
{
// echo \$input." ";
\$values = array(64,32,16,8,4,2,1);
\$stack = array();
foreach(\$values as \$value)
{
\$bit=\$value&\$input;
array_push(\$stack,\$bit);
}
// print_r(\$stack);
return \$stack;
}

//输出函数
function print_combination(\$input)
{
if(\$input>0){
\$results=bit_operation(\$input);
echo "t";
foreach(\$results as \$result)
{
// echo \$result;
if(\$result==64){echo a;}
elseif(\$result==32){echo b;}
elseif(\$result==16){echo c;}
elseif(\$result==8){echo d;}
elseif(\$result==4){echo e;}
elseif(\$result==2){echo f;}
elseif(\$result==1){echo g;}
}
print_combination(--\$input,\$values);
}
}

?>

2017-10-15 2 楼

Math_Combinatorics

<?php
require 'Math/Combinatorics.php';
\$arr = array('a','b','c','d','e','f','g');

\$combinatorics = new Math_Combinatorics;
foreach( range(1, count(\$arr)) as \$subset_size ) {
foreach(\$combinatorics->permutations(\$arr, \$subset_size) as \$p) {
echo join(' ', \$p), "n";
}
}

2017-10-11 1 楼

```function combination(\$arr)
{
\$len = count(\$arr);
foreach(\$arr as \$k => \$v)
{
\$total += pow(2,\$k);
}

\$ret = array();
for(\$i=1;\$i<=\$total;\$i++)
{
\$str = substr(str_repeat("0",\$len).decbin(\$i),-\$len);
\$tmparr = array_diff_key(\$arr,array_diff(str_split(\$str),array('1')));
\$ret[] = implode(\$tmparr,'');

}
return \$ret;

}

\$arr = array('a','b','c','d','e','f','g');
print_r(combination(\$arr));```

1833 主题
5641 回复
21107 人气