求php多数组组合排列算法
程序员文章站
2024-02-03 22:56:46
...
模拟四个数组:
$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
求一算法
但是跟这个不太一样
正解,那需要3个数字组合的时候,又该如何额实现,比如
最终需要得到:
147,148,149,157,158,159,167,168,169,247,248,249,257,258,259,267,268,269,347,348,349,357,358,359,367,368,369
上面写错了,多写了一个数组,
最终需要得到:
147,148,149,157,158,159,167,168,169,247,248,249,257,258,259,267,268,269,347,348,349,357,358,359,367,368,369
谢谢
$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
求一算法
回复讨论(解决方案)
网上看到一段代码:
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."
"; }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
正解,那需要3个数字组合的时候,又该如何额实现,比如
$list['a'] = array (1,2,3); $list['b'] = array (4,5,6); $list['c'] = array (7,8,9); $list['d'] = array (10,11,12);
最终需要得到:
147,148,149,157,158,159,167,168,169,247,248,249,257,258,259,267,268,269,347,348,349,357,358,359,367,368,369
$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);
最终需要得到:
147,148,149,157,158,159,167,168,169,247,248,249,257,258,259,267,268,269,347,348,349,357,358,359,367,368,369
本以为你是工作上遇到问题急需解决,没承想你是在研究算法
从算法角度看,你的两个题目都应是:对原始数据求组合( C(m,n) )的结果做 笛卡尔积 运算
代码就不贴了,你可以在精华区找到多个版本
本以为你是工作上遇到问题急需解决,没承想你是在研究算法
从算法角度看,你的两个题目都应是:对原始数据求组合( C(m,n) )的结果做 笛卡尔积 运算
代码就不贴了,你可以在精华区找到多个版本
谢谢
上一篇: Utf-8、gb2312都支持的汉字截取
下一篇: php解释为何要用isset()