r/programminghelp • • 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!

3 Upvotes

2 comments sorted by

1

u/[deleted] Nov 24 '19

When would you want to stop the function? And what language?

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:

  • text is your input

  • Put the base case here

  • first is the first character of text

  • rest is everything except the first character of text

  • recursiveCall is the result of calling shiftLargestChar on rest

  • largestFromRest is the last character from recursiveCall, which should be the largest character from rest

  • comparison is a boolean that compares first with largestFromRest

  • There 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.