Question

I have been asked to solve this question. Please suggest me how to solve this.

$string = "kkjnmnmnjjjnmn";

here I need to find consecutively repeated string of length 3. for example - kkj has occurred only once and jnm 2 times and nmn 3 times.

Starting from first character, going in right side direction, 3 consecutive characters which are repeated more than once should be the output.

Preg_match_all will result as nmn - 2 times and not as 3 times.

How to solve this?

Was it helpful?

Solution

    $string = "kkjnmnmnjjjnmn";
    $length = strlen($string);
    $pieces = [];
    for ($i = 0; $i < $length - 2; $i++) {
        $piece = substr($string, $i, 3);
        if (array_key_exists($piece, $pieces)) {
            $pieces[$piece] += 1;
        } else {
            $pieces[$piece] = 1;
        }
    }

// $pieces will contain what you need

OTHER TIPS

This one without using any build in functions, Try

$string = "kkjnmnmnjjjnmn";
$i = 0;
$strarr = array();
while(isset($string[$i+2])){
if(!isset($strarr[$string[$i].$string[$i+1].$string[$i+2]]))
    $strarr[$string[$i].$string[$i+1].$string[$i+2]] = 1;
else
    $strarr[$string[$i].$string[$i+1].$string[$i+2]] += 1;
$i++;
}
print_r($strarr);

Here's my thought.

$arr = array();
for ($i = 0; $i <= strlen($string) - 3; $i++) {
    $part = substr($string, $i, 3);
    if (array_key_exists($part, $arr)) {
        $arr[$part]++;
    } else {
        $arr[$part] = 1;
    }
}
foreach ($arr as $key => $value) {
  //output the result
}

well iam not a php expert but after examine the previous answers,i found an alter solution too here it is:

$string='aaaabcdeeeffaaabh';
$arr_str=array();
for($i=0;$i<strlen($string);$i++)
{
    if(in_array($string[$i],$arr_str[$char[$i]]))
    {
       $arr_str[$string[$i]]=1;
    }
    else
    {
       $arr_str[$string[$i]]+=1;
     }
}

 foreach($arr_str as $key => $value)
  {
    echo $key.' Repeats '.$value.' Times'.'<br/>';
  }

OUTPUT:

a Repeats 7 Times
b Repeats 2 Times
c Repeats 1 Times
d Repeats 1 Times
e Repeats 3 Times
f Repeats 2 Times
h Repeats 1 Times
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top