-1

I have the array:

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

And I intend to count the number of elements A that are included in consecutive chains with length more or equal 2. In the example I have three chains but i want count only two of them. Altogether result should be 5.

splash58
  • 26,043
  • 3
  • 22
  • 34

1 Answers1

0

Find consecutive chains of '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;
splash58
  • 26,043
  • 3
  • 22
  • 34