Home > Enterprise >  How to move all 'c' elements to the end with a recursive function using Kotlin?
How to move all 'c' elements to the end with a recursive function using Kotlin?

Time:09-30

How can I write code that returns the following output for this input:

Input: -> fffcccfff
Output: -> ffffffccc

My code so far:

fun toEnd(s: String): String {
    if (s[0] == 'x') {
        return (s.substring(1))   s[0]
    } else {
        return s[0]   toEnd(s.substring(1))
    }
}

But that doesn't work for the input above.

CodePudding user response:

There are three problems here.  To take the most serious first:

  • There's no termination condition.

You can't recurse for ever; there must be a point at which you stop.

As written, your code throws a StringIndexOutOfBoundsException, because it keeps calling itself for smaller and smaller strings; eventually, it calls itself on an empty string, and so the s[0] fails because there is no first character.

To fix this, you need to add a check that does something different if the string is small enough. You could check for an empty string, and just return the empty string; or you could check for a string with ≤ 1 characters, and return it (which avoids one last level of recursion).

  • It checks for the wrong character.

The question (and the desired output) asks about moving the letter 'c' to the end of the string; but the code tries to move the letter 'x' instead.

(Of course, this is trivial to fix.)

  • It doesn't recurse if the first character is matched.

So it will only ever move one instance of that character to the end.

To fix that, simply call toEnd() on the substring in both cases.

Here's a fixed version. (I've also converted it to a when and made it an expression body; that's not necessary, but illustrates the alternatives.)

fun toEnd(s: String): String = when {
    s.length <= 1 -> s
    s[0] == 'c' -> toEnd(s.substring(1))   s[0]
    else -> s[0]   toEnd(s.substring(1))
}

This is a good example of recursion. But it's probably worth noting that you wouldn't write production code like that, because it's very inefficient, creating shedloads of temporary String objects. 

  • Related