Count consecutive occurence of specific, identical

2019-08-27 04:32发布

I am trying to calculate a few 'streaks', specifically the highest number of wins and losses in a row, but also most occurences of games without a win, games without a loss.

I have a string that looks like this; 'WWWDDWWWLLWLLLL'

For this I need to be able to return:

  • Longest consecutive run of W charector (i will then replicate for L)
  • Longest consecutive run without W charector (i will then replicate for L)

I have found and adapted the following which will go through my array and tell me the longest sequence, but I can't seem to adapt it to meet the criteria above.

All help and learning greatly appreciated :)

    function getLongestSequence($sequence){
$sl = strlen($sequence);
$longest = 0;
for($i = 0; $i < $sl; )
{
$substr = substr($sequence, $i);
$len = strspn($substr, $substr{0});if($len > $longest)
$longest = $len;
$i += $len;
}
return $longest;
}
echo getLongestSequence($sequence);

2条回答
戒情不戒烟
2楼-- · 2019-08-27 05:09

You can achieve the maximum count of consecutive character in a particular string using the below code.

       $string = "WWWDDWWWLLWLLLL";
        function getLongestSequence($str,$c) {
        $len = strlen($str);
        $maximum=0;
        $count=0;
        for($i=0;$i<$len;$i++){
            if(substr($str,$i,1)==$c){
                $count++;
                if($count>$maximum) $maximum=$count;
            }else $count=0;
        }
        return $maximum;
        }
        $match="W";//change to L for lost count D for draw count
        echo getLongestSequence($string,$match);
查看更多
贼婆χ
3楼-- · 2019-08-27 05:17

You can use a regular expression to detect sequences of identical characters:

$string = 'WWWDDWWWLLWLLLL';
// The regex matches any character -> . in a capture group ()
// plus as much identical characters as possible following it -> \1+
$pattern = '/(.)\1+/';

preg_match_all($pattern, $string, $m);
// sort by their length
usort($m[0], function($a, $b) {
    return (strlen($a) < strlen($b)) ? 1 : -1;
});

echo "Longest sequence: " . $m[0][0] . PHP_EOL;
查看更多
登录 后发表回答