【问题标题】:count elements consecutive array php计算元素连续数组php
【发布时间】:2015-06-12 15:28:29
【问题描述】:

我有数组:

$type = ['A','A','A','E','E','E','A','E','A','A','E','E'];
          1   2   3                       4   5

我打算计算长度大于或等于 2 的连续链中包含的元素 A 的数量。在示例中,我有三个链,但我只想计算其中两个。总结果应该是 5。

【问题讨论】:

标签: php


【解决方案1】:

查找“CA”的连续链

$count = 0;
$link = array();                     // Here will be chain lengths

array_push($types, '');              // to work if the last item == 'CA'

foreach($types as $item) 
  if ($item == 'CA') $count++;       
  else if ($count) 
         { $link[] = $count; $count = 0; }  

rsort($link);                        // 3, 2, 1
$sum = 0;
foreach ($link as $i) 
   if ($i >= 2) $sum += $i;          // Count result
   else break;                       // Further chains are shorter than we want

echo $sum;

【讨论】:

    猜你喜欢
    • 2014-01-06
    • 2015-12-01
    • 2018-07-28
    • 2019-11-14
    • 1970-01-01
    • 2022-01-19
    • 2017-12-26
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多