如何在 PHP 中获取和生成重复的数字(子集)数组



我检查了代码,意识到它无法显示重复的数字

我的代码

<?php
/* Designated level for each exp
Level 2 - 23 exp
Level 3 - 34 exp
Level 4 - 45 exp
Level 5 - 56 exp
Level 6 - 68 exp
Level 7 - 79 exp
Level 8 - 90 exp
Level 9 - 101 exp
Level 10 - 112 exp
Level 11 - 123 exp
Level 12 - 134 exp
Level 13 - 145 exp
Level 14 - 156 exp
Level 15 - 168 exp
Level 16 - 179 exp
*/
$limit =  100000-99370;
// Level
$arrlevel = array ('Level 2','Level 3','Level 4','Level 5','Level 6','Level 7','Level 8','Level 9','Level 10','Level 11','Level 12','Level 13','Level 14','Level 15','Level 16');
// Exp
$array = array (23,34,45,56,68,79,90,101,112,123,134,145,156,168,179);
$array = array_filter($array, function($var) use ($limit) {
return ($var <= $limit);
});
$num = count($array);
$total = pow(2, $num);
$out = array();
for ($i = 0; $i < $total; $i++) {
$comb = array();
for ($j = 0; $j < $num; $j++) {
// is bit $j set in $i?
if (pow(2, $j) & $i){
$comb[] = $array[$j];
}
}
if (array_sum($comb) == $limit)
{
$out[] = $comb;
}
}
array_multisort(array_map('count', $out), SORT_ASC, $out);
$out = array_unique($out, SORT_REGULAR);
$m = 1;
$mapper = [
23 => "Level 2",
34 => "Level 3",
45 => "Level 4",
56 => "Level 5",
68 => "Level 6",
79 => "Level 7",
90 => "Level 8",
101 => "Level 9",
112 => "Level 10",
123 => "Level 11",
134 => "Level 12",
145 => "Level 13",
156 => "Level 14",
168 => "Level 15",
179 => "Level 16",
];
foreach($out as $result)
echo "<b>Possible Answer ". $m++. " : </b><br> " .implode(' , ', array_map(function($x) use ($mapper) {
return $mapper[$x] . " - " . $x;
}, $result))." 
<br><br>";

我的输入和输出

如果我输入 99318,
输出是这样的
可能的答案 1 :
级别 10 - 112 , 级别 11 - 123 , 级别 12 - 134 , 级别 13 - 145 , 级别 15 - 168
我也想生成重复的数字,

但它不能显示一些重复的数字 像这样回答 可能的答案 : 等级 4 - 45 , 等级 10 - 112 , 等级 11 - 123 , 等级

11 - 123 , 等级 12 - 134 , 等级 13 - 145

你可以看到有两个 11 - 123



我想要这样的

输出 可能的答案
: 等级 4 - 45 , 等级 10 - 112 , 等级 11 (x2( - 246 , 等级 12 - 134 , 等级 13 - 145
我想对所有重复的数字进行分组并将它们全部汇总

获取结果的一种选择是将另一个值传递给array_map array_count_values的结果。

然后在映射中,您可以确定根据索引显示数字的计数,就像映射器一样$countValues[$x]

例如

foreach($out as $result) {
$countValues = array_count_values($result);
echo "<b>Possible Answer " . $m++ . " : </b><br> " . implode(' , ',
array_map(function ($x) use ($mapper, $countValues) {
$strCount = $countValues[$x] > 1 ? " (" . $countValues[$x] . ")" : "";
return $mapper[$x] . $strCount . " - " . $x;
}, array_unique($result))) . "
<br><br>";
}

那会给你一个结果,比如

Possible Answer 1 :
Level 2 - 23 , Level 6 - 68 , Level 7 (x2) - 79 , Level 9 - 101 , Level 10 - 112 , Level 15 - 168 

Php 演示,作为测试,重复值 79 用于$array

最新更新