Home >Backend Development >PHP Tutorial >高分求一个算法,在线等待中...
<?PHP$arr=Array( Array('a','b','c'), Array('d','e','f'), Array('g','h','i'), //第二?array的??是未知的,?了方便?例所以只?了3?);$x3=iArray($arr,3);Echo '<pre class="brush:php;toolbar:false">',Var_Dump($x3),'';/**期望的?果是:array { 'adg','adh','adi', 'aeg','aeh','aei', 'afg','afh','afi', 'bdg','bdh','bdi', 'beg','beh','bei', 'bfg','bfh','bfi', 'cdg','cdh','cdi', 'ceg','ceh','cei', 'cfg','cfh','cfi',}/**/$x2=iArray($arr,2);Echo '
',Var_Dump($x2),'';/**期望的?果是:array { 'ad','ae','af', 'ag','ah','ai', 'bd','be','bf', 'bg','bh','bi', 'cd','ce','cf', 'cg','ch','ci', 'dg','dh','di', 'eg','eh','ei', 'fg','fh','fi',}/**/
好多小花花
$arr=Array( Array('a','b','c'), Array('d','e','f'), Array('g','h','i'), //第二?array的??是未知的,?了方便?例所以只?了3?); print_r(iArray($arr,3));print_r(iArray($arr,2)); function iArray($ar, $n) { if($n == 2) { //3取2的组合 $ar = array( array($ar[0], $ar[1]), array($ar[0], $ar[2]), array($ar[1], $ar[2]), ); }else $ar = array($ar); $res = array(); foreach($ar as $d) { $r = array_pop($d); while($d) { $t = array(); foreach(array_pop($d) as $x) foreach($r as $y) $t[] = $x . $y; $r = $t; } $res = array_merge($res, $r); } return $res;}Array
$arr=Array( Array('a','b','c'), Array('d','e','f'), Array('g','h','i'), //第二?array的??是未知的,?了方便?例所以只?了3?); print_r(iArray($arr,3));print_r(iArray($arr,2)); function iArray($ar, $n) { if($n == 2) { //3取2的组合 $ar = array( array($ar[0], $ar[1]), array($ar[0], $ar[2]), array($ar[1], $ar[2]), ); }else $ar = array($ar); $res = array(); foreach($ar as $d) { $r = array_pop($d); while($d) { $t = array(); foreach(array_pop($d) as $x) foreach($r as $y) $t[] = $x . $y; $r = $t; } $res = array_merge($res, $r); } return $res;}Array
iArray($ar,$n)
$n的取值??是: 2~6
我在代码中已经提示了要先求一下 M取N 的组合
而求组合的函数相信你的代码库中已经是有的
这是我用的
// combination 组合function combination( $arr, $num=0) { $len = count($arr); if($num == 0) $num = $len; $res = array(); for($i=1,$n=pow(2, $len);$i<$n;++$i) { $tmp = str_pad(base_convert($i, 10, 2), $len, '0', STR_PAD_LEFT); $t = array(); for($j=0;$j<$len;++$j) { if($tmp{$j} == '1') { $t[] = $arr[$j]; } } if(count($t) == $num) $res[] = $t; } return $res;}
function iArray($ar, $n) { $res = array(); foreach(combination($ar, $n) as $d) { $r = array_pop($d); while($d) { $t = array(); foreach(array_pop($d) as $x) foreach($r as $y) $t[] = $x . $y; $r = $t; } $res = array_merge($res, $r); } return $res;}