V
V
Valuvir2019-04-01 12:06:30
C++ / C#
Valuvir, 2019-04-01 12:06:30

What needs to be changed in the C++ code?

The program finds sequences of identical characters longer than 3 in a string and pushes these fragments into a two-dimensional array.

char s[]={"qhtnnnnnnfchjjjgeeeeejg   tdggv ddddddddd"};
  int z=0,l,o,k=0,q,len=strlen(s) ;
  char c[20][20];

  for(int i=0;i<len;i++){								
    for(int j=i+1;j<len;j++)						
    {							
      if (s[i]==s[j])
      {
        for (o=i,l=j;;l++)
        {
          if(s[o]==s[l])
          {
            z++;
          }
          else 
          {
            z=0;
            break;
          }	
          if (z>3)
          {
            for(q=0;q<z;q++) {c[k][q]=s[l];}
            c[k][q]='\0';
            k++;i=l+q;
          }
        }
      }
    }
  }

At the output, if the sequence is longer than 4, it pushes a fragment of 4 characters into the first subarray, 5 characters into the second, and so on. Shamanil, shamanil did not manage to fix it ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
StillDreamer, 2019-04-03
@StillDreamer

The answer to the question.
Your code is overcomplicated, but if you understand it, then the problem is with the loop in which the checks with z go.

for (o = i,l = j; ;l++)
{
     if (s[o] == s[l])
     {
          z++;
      }
      else 
      {
            z=0; 
            break;
      }	
      // Итак, что произойдёт в if'е ниже. Каждый раз, когда z > 3, будет добавляться строка в массив
     // Даже если текущая последовательность ещё не кончилась.     
      if (z > 3)
      {
          for (q = 0; q < z; q++) 
          { 
              c[k][q] = s[l];
          }
          c[k][q] = '\0';
          k++;
          i = l + q;
      }
}

Now for the code recommendations.
First, try to give meaningful names to variables. For example, z could be called current_sequence_length. So it's easier to debug and generally understand what's going on.
Second, don't skimp on spaces around assignments, arithmetic operators, and equal signs. https://google.github.io/styleguide/cppguide.html is a pretty good styleguide.
3. As already mentioned, it would be possible to use strings that are string, and built-in features.
4. If, without search algorithms and strings, your solution is still too complicated, it can be simplified.
As an outline
int start_pos = 0;
int cur_pos = 1;
while (cur_pos < len)
{
    // Начинаем сравнивать
    while (cur_pos < len && s[start_pos] == s[cur_pos]) 
    {
        // Просто двигаемся к следующему элементу, пока они одинаковые
         ++cur_pos;
    }

    if (cur_pos - start_pos > 3) // Нашлось 4 или более одинаковых символа подряд
    {
        // Копируем, мне слишком лень писать этот кусок :) Но тут надо корректно обработать
       // ситуацию с концом строки
       // А ещё не забываем подвинуть start_pos и cur_pos
       start_pos = cur_pos;
       ++cur_pos;
    }
}

Можно вообще без вложенных циклов, можно ещё как-то иначе. Я про примерную суть.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question