I got this exercise (it's not homework or an assignment, just practice) that asks for a program that replaces the characters in a string by the greatest character on the right using recursive functions, no loops allowed.
If I have a string acbcba
the function has to return ccccba
.
One thing I've tried with the loops for the string is this, to maybe try to turn it into a recursion if it worked:
void nextGreatest(char *str, int size)
{
int max_from_right = str[size-1];
str[size-1] = -1;
for(int i = size-2; i >= 0; i--)
{
int temp = str[i];
str[i] = max_from_right;
if(max_from_right < temp)
max_from_right = temp;
}
}
Output: cccba
I think the issue is that it doesn't count the characters that don't have to be replaced.
There was also another example using python I found and tried to change to C (MAX is a macro from here):
void nextGreatest(char *arr, int rev_i, int maxnum){
if (rev_i == strlen(arr) - 1){
arr[0] = maxnum;
return;
}
int i = strlen(arr) - 1 - rev_i;
arr[i], maxnum = maxnum, MAX(maxnum, arr[i]);
return nextGreatest(arr, rev_i + 1, maxnum);
}
Output: ~bccba