$a = array(a,b,c,d,e,f,g,h,i,j,k,l);
将$a这个数组中的元素分成6个一组,计算出他们的组合结果,如:
abcdef
abcdeg
abcdeh
abcdei
abcdej
abcdek
abcdel
abcdfg
abcdfh
......
请高手们帮帮忙。
8 个解决方案
#1
允许重复吗?
#2
不能重复,如果重复可以用array_unique处理就可以了。
#3
/**
* 函数 combination
* 功能 m取n的组合函数
**/
if(! function_exists('combination')):
function combination($ar, $k, $m=0, $a=array()) {
static $ret = array();
if($m == 0) {
$m = count($ar);
$ret = array();
}
for($i=$m; $i>=$k; $i--) {
$a[$k-1] = $ar[$i-1];
if($k > 1) {
combination(&$ar, $k-1, $i-1, $a);
}else {
array_unshift ($ret, array_reverse($a));
}
}
return $ret;
}
endif;
#4
调用参数能说明一下吗?
#5
$a = array(a,b,c,d,e,f,g,h,i,j,k,l);
$ar = combination($a, 6);
$ar = combination($a, 6);
#6
这个函数调用能给个例子吗?
#7
$ar = combination($a, 6);
得到的是这样的数组
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
[1] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => g
)
如果你希望每组连接成串,可以
$r = array_map(create_function('$v', 'return join("", $v);'), $ar);
print_r($r);
Array
(
[0] => abcdef
[1] => abcdeg
[2] => abcdfg
[3] => abcefg
[4] => abdefg
[5] => acdefg
[6] => bcdefg
[7] => abcdeh
[8] => abcdfh
#8
弄了半天也不对,气死我了,不搞了!
<?php
static $a = array(a,b,c,d,e,f,g,h,i,j,k,l);
$max = count($a);
$n = 6;
$work = array(0,1,2,3,4,5);
$complated = false;
do
{
for ($i=0; $i<count($work); $i++)
{
echo $a[$i];
}
echo "<br \>";
$j=count($work)-1;
while($j>0 && $work[$j]>=count($a)-count($work)+$j)
{
$j--;
}
if ($j >= 0)
{
++$work[$j];
for ($k=$j+1; $k<count($work); $k++)
{
$wokr[$k] = $work[$j]+$k - $j;
}
}
else
{
$complated = true;
}
}while(!$complated);
?>
#1
允许重复吗?
#2
不能重复,如果重复可以用array_unique处理就可以了。
#3
/**
* 函数 combination
* 功能 m取n的组合函数
**/
if(! function_exists('combination')):
function combination($ar, $k, $m=0, $a=array()) {
static $ret = array();
if($m == 0) {
$m = count($ar);
$ret = array();
}
for($i=$m; $i>=$k; $i--) {
$a[$k-1] = $ar[$i-1];
if($k > 1) {
combination(&$ar, $k-1, $i-1, $a);
}else {
array_unshift ($ret, array_reverse($a));
}
}
return $ret;
}
endif;
#4
调用参数能说明一下吗?
#5
$a = array(a,b,c,d,e,f,g,h,i,j,k,l);
$ar = combination($a, 6);
$ar = combination($a, 6);
#6
这个函数调用能给个例子吗?
#7
$ar = combination($a, 6);
得到的是这样的数组
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
[1] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => g
)
如果你希望每组连接成串,可以
$r = array_map(create_function('$v', 'return join("", $v);'), $ar);
print_r($r);
Array
(
[0] => abcdef
[1] => abcdeg
[2] => abcdfg
[3] => abcefg
[4] => abdefg
[5] => acdefg
[6] => bcdefg
[7] => abcdeh
[8] => abcdfh
#8
弄了半天也不对,气死我了,不搞了!
<?php
static $a = array(a,b,c,d,e,f,g,h,i,j,k,l);
$max = count($a);
$n = 6;
$work = array(0,1,2,3,4,5);
$complated = false;
do
{
for ($i=0; $i<count($work); $i++)
{
echo $a[$i];
}
echo "<br \>";
$j=count($work)-1;
while($j>0 && $work[$j]>=count($a)-count($work)+$j)
{
$j--;
}
if ($j >= 0)
{
++$work[$j];
for ($k=$j+1; $k<count($work); $k++)
{
$wokr[$k] = $work[$j]+$k - $j;
}
}
else
{
$complated = true;
}
}while(!$complated);
?>