php算法笔试题
有一二维数组
array(array(1,2,3,4,5,6,7,8,9),
array(1,2,3,4,5,6,7,8,9),
array(1,2,3,4,5,6,7,8,9),
array(1,2,3,4,5,6,7,8,9),
array(1,2,3,4,5,6,7,8,9),
)
每个数组取不同的5个数为组成1组 求问有多少种组合数组[数组0]取出的值 != 数组[数组1]取出的值!= 数组[数组2]取出的值 != 数组[数组3]取出的值 != 数组[数组4]取出的值 组成一组;为一组这种求解
4 回答
小唯快跑啊
TA贡献1863条经验 获得超2个赞
for ($i = 1; $i < 10; $i++) {
for ($j = 1; $j < 10; $j++) {
if ($i == $j) {
continue;
}
for ($k = 1; $k < 10; $k++) {
if ($i == $k || $j == $k) {
continue;
}
for ($l = 1; $l < 10; $l++) {
if ($i == $l || $j == $l || $k == $l) {
continue;
}
for ($m = 1; $m < 10; $m++) {
if ($i == $m || $j == $m || $k == $m || $l == $m) {
continue;
}
$arr[] = $i . $j . $k . $l . $m;
}
}
}
}
}
echo '<pre>';
var_dump($arr);die();
//方法二
//不过可以应对不同的数组参数,不过参数越多,性能就越糟糕
set_time_limit(0);
$arr =[
[1,2,3,4,5,6,7,8,9],
[1,2,3],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[5,6,7,8,9],
];
$count = count($arr);
//需求:$arr每个子数组取出一个1个不同的数,进行组合
$main = [];
for($i=0; $i<$count; $i++){
$dep = $arr[$i];
$sock = $main;
$main = [];
for ($j=0; $j <count($sock) ; $j++) {
$split = str_split($sock[$j]);
for ($k=0; $k < count($dep); $k++) {
if(in_array($dep[$k], $split)){
continue;
}
$number = $sock[$j].$dep[$k];
if(!in_array($number, $main)){
$main[]=$number;
}
}
}
$main = empty($main)?$dep:$main;
}
echo '<pre>';
var_dump($main);
die();
- 4 回答
- 0 关注
- 373 浏览
添加回答
举报
0/150
提交
取消