![](/img/trans.png)
[英]How to print all possible variations without repetitions of array for given range?
[英]Print all combination of sub range within a given array
我想在給定的數組中打印子范圍的所有組合。 我有一個y個元素的數組,我想從中打印連續子范圍的所有組合。
約束是:每個子范圍應至少包含2個元素,並且子范圍中的每個元素應連續。 它應該共享每個元素的相同邊框。
例如,我們有7個元素組成的數組[11,12,13,14,11,12,13]
因此,子范圍組合的總數將為[7 * (7-1) /2] = 21
因此,輸出將如下所示:
11,12
12,13
13,14
14,11
11,12
12,13
11,12,13
12,13,14
13,14,11
...
11,12,13,14 and so on (total 21 combination as per above array)
我們不應該打印任何不連續的組合。 示例: [11,12,14]
是無效的組合,因為它跳過了元素之間的“ 13”。
我能夠打印2個元素的組合,但是我很難再打印2個元素的組合。
以下是到目前為止我嘗試過的。
$data=array("11","12","13","14","11","12","13");
$totalCount=count($data);
for($i=0;$i<$totalCount;$i++){
if(($i+1) < ($totalCount)){
echo "[".$data[$i].",".$data[$i+1]."]<br>";
}
}
您可以這樣做:
$arr = [11,12,13,14,11,12,13];
function genComb($arr, $from = 1, $to = -1) {
$arraySize = count($arr);
if ($to == -1) $to = $arraySize;
$sizeLimit = $to + 1;
for ($i = $from; $i < $sizeLimit; $i++) { // size loop
$indexLimit = $arraySize - $i + 1;
for ($j = 0; $j < $indexLimit; $j++) { // position loop
yield array_slice($arr, $j, $i);
}
}
}
$count = 0;
foreach (genComb($arr, 2) as $item) {
echo implode(',', $item), PHP_EOL;
$count++;
}
echo "total: $count\n";
Casimir et Hippolyte速度更快,但是您可以通過獨立處理每個連續部分來獲得巨大的性能:
function getCombos(&$data) {
$combos = array();
$count = count($data);
$i = 0;
while ($i < $count) {
$start = $i++;
while ($i < $count && $data[$i - 1] + 1 == $data[$i]) // look for contiguous items
$i++;
if ($i - $start > 1) // only add if there are at least 2
addCombos($data, $start, $i, $combos); // see other answer
}
return $combos;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.