Heim >Backend-Entwicklung >PHP-Tutorial >求php多数组组合排列算法
模拟四个数组:
$list [‘a’] = array (1,2,3);
$list [‘b’] = array (4,5,6);
$list [‘c’] = array (7,8,9);
要求组合成这样:14,15,16,17,18,19,24,25,26,27,28,29,34,35,36,37,38,39,47,48,49,57,58,59,67,68,69
求一算法
网上看到一段代码:
<?php class sufa{ public function main(){ $list [‘a’] = array (1,2,3); $list [‘b’] = array (1,2); $list [‘c’] = array (1,2,3,4); // $list [‘f’] = array (1,2,3,4,5); // $list [‘d’] = array ("+","-","*","/","%"); foreach($list[‘a’] as $v){ $this->getsulie($list,$v,1); } } function getsulie($list,$content,$deep){ $i=0; if($deep>count($list)){ return; } foreach($list as $k=>$v){ if($i==$deep){ foreach($list[$k] as $vv){ $vv = $content.$vv; if($deep==count($list)-1){ echo $vv."<br/>"; }else { $this->getsulie($list,$vv,$deep+1); } } break; } $i++; } return; } } $s = new sufa(); $s->main(); ?>
递归不太会用,求大神指点
$list['a'] = array (1,2,3);$list['b'] = array (4,5,6);$list['c'] = array (7,8,9);foreach($list as $key=>$row) { unset($list[$key]); foreach($row as $col) { foreach($list as $r) foreach($r as $v) $res[] = $col . $v; }}echo join(',', $res);14,15,16,17,18,19,24,25,26,27,28,29,34,35,36,37,38,39,47,48,49,57,58,59,67,68,69
$list['a'] = array (1,2,3);$list['b'] = array (4,5,6);$list['c'] = array (7,8,9);foreach($list as $key=>$row) { unset($list[$key]); foreach($row as $col) { foreach($list as $r) foreach($r as $v) $res[] = $col . $v; }}echo join(',', $res);14,15,16,17,18,19,24,25,26,27,28,29,34,35,36,37,38,39,47,48,49,57,58,59,67,68,69
$list['a'] = array (1,2,3); $list['b'] = array (4,5,6); $list['c'] = array (7,8,9); $list['d'] = array (10,11,12);
$list['a'] = array (1,2,3);$list['b'] = array (4,5,6);$list['c'] = array (7,8,9);foreach($list as $key=>$row) { unset($list[$key]); foreach($row as $col) { foreach($list as $r) foreach($r as $v) $res[] = $col . $v; }}echo join(',', $res);14,15,16,17,18,19,24,25,26,27,28,29,34,35,36,37,38,39,47,48,49,57,58,59,67,68,69
$list['a'] = array (1,2,3); $list['b'] = array (4,5,6); $list['c'] = array (7,8,9);
本以为你是工作上遇到问题急需解决,没承想你是在研究算法
从算法角度看,你的两个题目都应是:对原始数据求组合( C(m,n) )的结果做 笛卡尔积 运算
代码就不贴了,你可以在精华区找到多个版本
本以为你是工作上遇到问题急需解决,没承想你是在研究算法
从算法角度看,你的两个题目都应是:对原始数据求组合( C(m,n) )的结果做 笛卡尔积 运算
代码就不贴了,你可以在精华区找到多个版本