• Write a function Reduction that takes a string S and eliminates from S every sequence of 3 or more consecutive occurrences of the same character. The function returns 1 if it finds at least one sequence to eliminate from S and 0 if no sequence to eliminate.
    Ex: If the string S is “aabbbacdddddf”, then after calling the function S becomes “aaacf” and the function returns 1.
    If the string S is “aabcabbdf”, then after calling the function S remains “aabcabbdf” and the function returns 0.
  • Write a function RecReduction that takes a string S and recursively calls the function Reduction while there are at least one sequence to eliminate from S.
    If the string is “aabbbacdddddf” then after calling the function the string becomes “cf”

Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <string.h>

int Reduction(char str[])
{
    int nb=0;
    int i, j, k;
    for(i=2;str[i];i++)
    {
        if(str[i]==str[i-1] && str[i-1]==str[i-2])
        {
            j=i;
            k=3;
            while(str[j]==str[j+1])
            {    
                j++;
                k++;
            }
            for(j=j+1;str[j];j++)
                str[j-k] = str[j];
            str[j-k]='\0';
            nb++;
        }
    }
    return nb>0;
}

void RecReduction(char str[])
{
    while(Reduction(str));
}

int main()
{
    char str[100]="aabcabbdf" ,str1[100]="aabbbacdddddf";
    printf("%d %s\n",Reduction(str), str);
    RecReduction(str1);
    printf("%s\n",str1);
    return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Graph Edge Property