2

I would like to count numeric values in a group of two for equal values. For example for list of values 1,2,3,3,3,3,3,3,3,3,5,5,6

I should have 1,2,(3,3),(3,3),(3,3),(3,3),(5,5),6

That is when I decide to count the first (3,3) are counted as 1. Therefore in this case I should have $count=8 instead of $count=13 for all values. I have tried to do some for loops and if statements but I get wrong results. Any idea is highly appreciated. Thanks

Note: the pairs have to be adjacent to be regarded as 1.

6
  • Do the pairs have to be adjacent to be regarded as 1? Commented Jun 4, 2012 at 6:42
  • Do you mean to get distinct value count? Commented Jun 4, 2012 at 6:44
  • Whilst you loop, keep track of the previous loop's number in a variable, and in the current iteration if the value is the same then do not increment the counter, and clear the tracking variable so your next iteration starts again. You should also reset the tracking variable with the current value when the previous value doesn't match. Commented Jun 4, 2012 at 6:44
  • so 1,2,1,2 is counted as 4, not 2, correct? Commented Jun 4, 2012 at 6:45
  • Note really. If distinct values, only a maximum of 2 they should be grouped together i.e for values 3,3,3 we have (3,3),3 hence the count obtained is 1,2 instead of 1,2,3 Commented Jun 4, 2012 at 6:46

2 Answers 2

4
$list = array(1,2,3,3,3,3,3,3,3,3,5,5,6);
$counter = 0;
foreach($list as $number)
{
  if(isset($previous) and $previous === $number)
  {
    unset($previous);
  }
  else
  {
    $previous = $number;
    $counter++;
  }
}
echo $counter; // 8
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Scuzzy.I have never use the unset() before. You have taught me something new. It works perfectly too +1 for that
consider accepting his answer by clicking on the V sign on the top left of his answer
3

Regular expression solution with back references:

$s = '1,2,3,3,3,3,3,3,3,3,5,5,6';

echo count(explode(',', preg_replace('/(\d+),\\1/', '\\1', $s)));

Output:

8

The regular expression matches a number and then uses a back reference to match the number adjacent to it. When both are matched, they are replaced by one number. The intermediate result after the preg_replace is:

1,2,3,3,3,3,5,6

After that, the count is performed on the comma separated values.

3 Comments

Missed the counting requirement earlier on :)
No problem. You made it easy,fewer lines of code than I expected.Thanks a bunch.It works perfect.
@nairobicoder great, I hope you can understand the regular expression :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.