Me and my classmate completed this exercise in two different ways,
Is there a simpler way to complete this task that is more rookie-friendly?
The reason I'm asking is because this is one of the exercises that we should dig into and really understand before our examination.
The automated judge didn't approve my first solution, using a function of my own creation, (this works for all testcases that I tried):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void compress(char *str);
int main()
{
char str[60];
while(scanf("%59s", str)==1){
compress(str);
printf("%s\n", str);
return 0;
}
}
void compress(char *str)
{
size_t len = strlen(str);
if(len <= 1)
return;
for(size_t i = 1; i < len; )
{
if(str[i] == str[i - 1])
{
memmove(&str[i], &str[i + 1], (len - (i + 1) + 1));
--len;
}
else
++i;
}
}
The automated judge approved my second solution, doing it all inside main function, even though it didn't work for all testcases that I tried. :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s[60];
char *ptr;
int d;
int str_len;
int ptr_len;
while(scanf("%59s", s)==1)
{
str_len = strlen(s);
for (int i = 0; i < str_len; i++)
if (s[i] == s[i+1])
d = d + 1;
ptr_len = str_len - d;
d = 0;
ptr = malloc (ptr_len * sizeof(char));
for (int i = 0; i < str_len; i++){
if (s[i] == s[i+1])
d = d + 1;
else
ptr[i-d] = s[i];
}
for (int i = 0; i < ptr_len; i++)
s[i] = ptr[i];
s[ptr_len] = '\0';
printf("%s\n", s);
d = str_len = ptr_len = 0;
free(ptr);
}
}