[英]Print all combination of sub range within a given array
I want to print all combination of sub range in an given array. 我想在给定的数组中打印子范围的所有组合。 I have an array of y number of elements in it from which I want to print all combination of contiguous sub range.
我有一个y个元素的数组,我想从中打印连续子范围的所有组合。
Constraint is : each sub range should have at least 2 elements and each element in sub range should be contiguous. 约束是:每个子范围应至少包含2个元素,并且子范围中的每个元素应连续。 It should share same border of each element.
它应该共享每个元素的相同边框。
For example, We have an array of 7 elements [11,12,13,14,11,12,13]
例如,我们有7个元素组成的数组
[11,12,13,14,11,12,13]
So, the total number of sub range combination will [7 * (7-1) /2] = 21
因此,子范围组合的总数将为
[7 * (7-1) /2] = 21
So, the Output will be something like this: 因此,输出将如下所示:
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)
we should not print any combination which is not contiguous. 我们不应该打印任何不连续的组合。 example:
[11,12,14]
is not valid combination as it skips the element "13" in between. 示例:
[11,12,14]
是无效的组合,因为它跳过了元素之间的“ 13”。
I am able to print the combination with 2 elements but i am having difficulty in printing more then 2 elements combination. 我能够打印2个元素的组合,但是我很难再打印2个元素的组合。
Below is what I have tried so far. 以下是到目前为止我尝试过的。
$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>";
}
}
You can do that: 您可以这样做:
$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 was faster, but you can gain huge performance by processing each contiguous section independently: 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.