how to get the highest repetition index (source 0) within a php string

Asked

Viewed 50 times

0

Ex: Run::posicaoMaiorRepeticao(‘ccddddeee') must return 2, since dddd is the highest repetition and its initial index is 2.

I’ve come this far, but the main thing of Function I haven’t been able to do yet:

class Run
{
    public static function posicaoMaiorRepeticao($str)
    {
        throw new Exception(‘Implementar’);
    }
}

echo Run:: posicaoMaiorRepeticao('abbcccddddeeeeeefffffffffggg');
// 16


echo Run:: posicaoMaiorRepeticao('ddddeeeeeefffffffffgggggggggggggggggghhhhh’);
// 19
  • 1

    What would happen if it were abcaaaaaaaaaaaa? Would return 0 or would return 3?

  • I did what you asked in C#, I’m translating into php.

2 answers

0

This does not work with multibyte characters!

In the condition of posting could simply do:

$string = 'ddddeeeeeefffffffffgggggggggggggggggghhhhh';

$QntPorCaractere = count_chars($string, 1);

arsort($QntPorCaractere);
reset($QntPorCaractere);

echo strpos($string, key($QntPorCaractere));

Test this.

This will return the position of the first letter that is most repeating in the string. That is, if it is gabcdefggg would be 0, because the g is the most repeated and the first position of g is in 0.


The count_chars using the parameter 1 will return exactly the amount of occurrences (in value) and what was the character (in key) of the array, ie:

array(5) {
  [100]=>
  int(4)
  [101]=>
  int(6)
  [102]=>
  int(9)
  [103]=>
  int(18)
  [104]=>
  int(5)
}

In this case the 103 is the g, in the ASCII table, so that we can order, after all we want the one that has more occurrences, we use the arsort().

So we got the 103, which is contained in the array key using key($QntPorCaractere) and use it inside the strpos() that picks up the first occurrence.


It may seem wrong to use strpos($string, 103); instead of using something like strpos($string, pack('C', 103));. But the PHP manual says that "If Needle is not a string, it is converted to an integer and Applied as the ordinal value of a Character." then as it is in the format int o 103 passes to g internally by strpos.

0

I don’t know if there is a php function to do this more practically, but I made a very simple algorithm that does this:

<?php
function posicaoMaiorRepeticao($x)
{
    $index = -1;
    for ($i=0;$i<strlen($x);$i++)
    {
        if ($ultimo != $x[$i])
        {
            $ultimocount = $count;
            $count = 0;
            $ultimo = $x[$i];
        }
        else
        {
            $count++;
            if ($count > $ultimocount)
                $index = strpos($x, $x[$i]);
        }
    }
    return $index;
}

$n = "abbcccddddeeeeeefffffffffggg";
echo posicaoMaiorRepeticao($n); //Output: 16

See working on Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.