php - PHP:没有排列的组合
问题描述
这段代码为我提供了长度为 x 的 n 个值的所有可能组合,得到 n 的总和。
function GETall_distri_pres($n_valeurs, $x_entrees, $combi_presences = array()) {
if ($n_valeurs == 1) {
$combi_presences[] = $x_entrees;
return array($combi_presences);
}
$combinaisons = array();
// $tiroir est le nombre de chaussettes dans le tiroir suivant
for ($tiroir = 0; $tiroir <= $x_entrees; $tiroir++) {
$combinaisons = array_merge($combinaisons, GETall_distri_pres(
$n_valeurs - 1,
$x_entrees - $tiroir,
array_merge($combi_presences, array($tiroir))));
}
return $combinaisons;
}
我只需要生成唯一的分布,例如没有 [2,1,1,0] 和 [1,2,1,0],只有 [2,1,1,0]。
var_dump(GETall_distri_pres(3,3)) 将给出:
array (size=10)
0 =>
array (size=3)
0 => int 0
1 => int 0
2 => int 3
1 =>
array (size=3)
0 => int 0
1 => int 1
2 => int 2
2 =>
array (size=3)
0 => int 0
1 => int 2
2 => int 1
3 =>
array (size=3)
0 => int 0
1 => int 3
2 => int 0
4 =>
array (size=3)
0 => int 1
1 => int 0
2 => int 2
5 =>
array (size=3)
0 => int 1
1 => int 1
2 => int 1
6 =>
array (size=3)
0 => int 1
1 => int 2
2 => int 0
7 =>
array (size=3)
0 => int 2
1 => int 0
2 => int 1
8 =>
array (size=3)
0 => int 2
1 => int 1
2 => int 0
9 =>
array (size=3)
0 => int 3
1 => int 0
2 => int 0
你有什么想法?
解决方案
这将是一种方法:在返回计算集之前,您通过创建一个新的关联数组来过滤它们,使用规范化的排列作为键。这将导致排列覆盖自己,因此只有一个会被保留:
<?php
function GETall_distri_pres($n_valeurs, $x_entrees, $combi_presences = array()) {
if ($n_valeurs == 1) {
$combi_presences[] = $x_entrees;
return array($combi_presences);
}
$combinaisons = array();
// $tiroir est le nombre de chaussettes dans le tiroir suivant
for ($tiroir = 0; $tiroir <= $x_entrees; $tiroir++) {
$combinaisons = array_merge($combinaisons, GETall_distri_pres(
$n_valeurs - 1,
$x_entrees - $tiroir,
array_merge($combi_presences, array($tiroir))));
}
// filter out permutations
$filteredCombinations = [];
array_walk($combinaisons, function($entry) use(&$filteredCombinations) {
arsort($entry);
$filteredCombinations[join('', $entry)] = $entry;
});
return array_values($filteredCombinations);
}
$result = GETall_distri_pres(3, 3);
print_r($result);
输出显然是:
Array
(
[0] => Array
(
[0] => 3
[1] => 0
[2] => 0
)
[1] => Array
(
[0] => 2
[1] => 1
[2] => 0
)
[2] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
)
推荐阅读
- php - 浏览器上未显示 PHP 错误,仅在日志中显示 - php 7.1
- javascript - 使用下拉反应带更改状态
- sql - 用其他表中的数据更新一个表。(有补充)
- matlab - 如何在matlab中从矩阵中显示具有自定义透明度的图像?
- azure-devops - Azure Devops 2019 上 CI/CD 的 Git 分支策略
- asp.net-mvc - MVC 控制器将 POST 的 JSON 处理为字符串
- smooth-scrolling - 在其他人的帖子中发现的滚动平滑代码中发现了错误,但不知道如何修复
- flutter - 更新设置状态内的变量
- svg - 将 SVG 字体转换为 SVG 路径
- python - Numpy Matrix 插入的意外结果,这是如何工作的?