Tuesday, June 14, 2016

changeXY - Recursive - Java & C#

Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars have been changed to 'y' chars.

changeXY("codex") → "codey"
changeXY("xxhixx") → "yyhiyy"
changeXY("xhixhix") → "yhiyhiy"
Java :
1
2
3
4
5
6
public String changeXY(String str) {
  if(str.length() < 1) return "";
  char temp = str.charAt(str.length()-1);
  if(temp == 'x') temp = 'y';
  return changeXY(str.substring(0,str.length()-1))+temp;
}

Test Result:

C#:
1
2
3
4
5
6
7
public static String changeXY(String str)
        {
            if (str.Length < 1) return "";
            Char temp = str[str.Length - 1];
            if (temp == 'x') temp = 'y';
            return changeXY(str.Substring(0, str.Length - 1)) + temp;
        }

Test Result :

countHi - Recursive

Given a string, compute recursively (no loops) the number of times lowercase "hi" appears in the string.

countHi("xxhixx") → 1
countHi("xhixhix") → 2
countHi("hi") → 1

C# :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  public static int countHi(String str)
        { 
            //stop condition
            if (str.Length < 2) return 0;

            //Process
            int index = str.IndexOf("hi");
            if (index < 0) return 0;
            return 1 + countHi(str.Substring(index + 1, str.Length - (1 + index)));
           
        }

Result :