r/programminghelp • u/buenaflor • Nov 24 '19
Find largest character by ASCII value in a string and insert it at the end recursively
Hey,
one part of my homework assignment is this exercise which I haven't been able to figure out to do.
So basically I have to find the largest character in a String (ASCII value) and then insert it at the end.
The catch is that I have to implement this recursively and I have to work with the predefined method parameters so I can't change anything here.
"String shiftLargestChar(String text)"
Example:
"taabkeuhm" -> "aabkeuhmt"
Any help is appreciated!
1
u/jakbrtz Nov 24 '19 edited Nov 24 '19
My answer will only focus on the recursion part of the question.
Let's start with the base case. This would be when the problem is very simple and requires (nearly) no processing. In this question, you know that when the length of your input is 1 (or 0) then the output should be the same as the input.
When you're given a string, there are two possibilities: the first character is the largest character, or the first character is not the largest character. I'm going to ignore the fact that the largest character can appear twice in the input.
A useful tip for recursion is to ask yourself what the output should be if it works properly. For this question, the largest character from your input should always be at the end of the output.
Now for the coding part. I'm not going to give you the answer, but I will show you how I would structure my answer:
textis your inputPut the base case here
firstis the first character oftextrestis everything except the first character oftextrecursiveCallis the result of callingshiftLargestCharonrestlargestFromRestis the last character fromrecursiveCall, which should be the largest character fromrestcomparisonis a boolean that comparesfirstwithlargestFromRestThere are two possible outputs for the function, depending on what we get for
comparison. I'm leaving it up to you to determine what they are.
Personally I don't think this is a good way to teach students how to do recursive functions, because it would be easier to do this using a loop.
1
u/[deleted] Nov 24 '19
When would you want to stop the function? And what language?