Java recursion problem

Hi,

i´m working on an assignment which i can´t get done. i´m hoping that maybe someone can help me out.

The task is to build a method which generates a String based on two other Strings "a" and "b".

In the newly generated String, every occures of the Chars from "a" which are not in "b" should be replaced by a "_".

Spaces shouldn´t be replaced. The comparison is non casesensitive and the return value needs to be in uppercase.

The twist is that the task needs to be solved recursevely so no loops are allowed. Furthermore, the following methods are not allowed: split(), mathes(), replaceAll() and replaceFirst(). Regexe´s are not allowed too.

Some examples for the method call and the expected output:

String result = blank("Hello World", "ell");

System.out.println(result); // => ELL __L

System.out.println(blank("abc def ghj", "a")); // => A__ _ _

​

I thought that i can solve it by using a pointer which i increment every time but since the variables are only reachable inside the method itself i wouldn´t help me.

Anohter idea was to simply remote every char from String a at index 0 if it does not match with the char from String b at index 0.

Can anyone help me out with this one?

Posted Dec 27, 2019, 9:23 PM UTC

14
AutoModeratorMOD•

To all following commenters: please, do not bring up the old circlejerk jokes/memes about recursion ("Understanding recursion...", "This is recursion...", etc.). We've all heard them n+2 too many times.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1
POGtastic•

Consider the following functions:

String replaceUnderscores(String a, String b, int index, String result = "") {
    if (index >= a.length) {
        // Base case - you're done with the string
    }

    // Call another (recursive) function that determines whether a[index] is in b. Set a Boolean value.

    // Recursive call, adding a character to result and incrementing index
}

bool isNotInString(char c, String b, int index) {
    if (index >= b.length) {
        // Base case - you're done with the string and haven't found anything
    }

    // Do your comparison, either returning false or recursively calling the function with an incremented index.
}

Silly Answer: I don't see String.chars() in that list of prohibitions, so streams are on the menu, boys! https://repl.it/@pogtastic/MoreFun

Professors love it when you write code like this.

1
GreedyScienceOP•

Thanks for your help, but in this case loops are forbidden. Your method uses a for-each loop which will render this solution as not valid and the list of parameters of the method does not match with the calls from the main method i´ve posted.
I appreciate your help though

1
POGtastic•

Whoops, edited.

1