Laura Maria
Laura Maria

Reputation: 9

How to use recursion to create a searies of substrings in java

So, the task is to create a string that makes a progression throughout the letters of a string, returning a substring progressively longer. For example if the input is Book, the answer would be: BBoBooBook . For the input Soup the method would return SSoSouSoup. I want to write it recursively. In my current method I receive no error but at the same time no anwer from the compiler.

public static String stringProgression(String str) {
        int index = 1;
        String result = "";
        if (str.length() == 0) {
            return "" ;
        } else while (index <= str.length()); {
                result = result + stringExplosion(str.substring(0, index));
                index++;
        } 
        return result;
    }

Upvotes: 0

Views: 65

Answers (2)

Holger
Holger

Reputation: 298123

In your code, you are using two different method names, stringProgression and stringExplosion.

Further, you have a while loop with a semicolon, while (index <= str.length()); which forms an empty loop. Since index doesn’t change in this empty loop, it will be an infinite loop when the condition is fulfilled.

Generally, a while loop contradicts the intent to have a recursive solution.

To find a recursive solution to a problem, you have to find the self-similarity in it. I.e. when you look at the intended result for Book, BBoBooBook, you can recognize that the beginning, BBoBoo is the right result for the string Boo, and BBo is the right result for Bo. So, the original string has to be appended to the result of a recursive evaluation of the substring:

public static String stringProgression(String str) {
    if(str.isEmpty()) {
        return str;
    }
    return stringProgression(str.substring(0, str.length() - 1)) + str;
}

An alternative, shorter syntax for the same is:

public static String stringProgression(String str) {
    return str.isEmpty()? str: stringProgression(str.substring(0, str.length() - 1)) + str;
}

Upvotes: 1

GregoAvg
GregoAvg

Reputation: 116

Check this one:

    private static String doStringProgression(String str, String res, int length) {
        if(length > str.length()) {
            return res;
        }
        return doStringProgression(str, res + str.substring(0, length), length + 1);
    }

And you can call the method with input like in the following example:

    public static String stringProgression(String str) {
        return doStringProgression(str, "", 1);
    }

Upvotes: 0

Related Questions