Tuesday, June 14, 2016

changePi - Recursive - Java & C#

Given a string, compute recursively (no loops) a new string where all appearances of "pi" have been replaced by "3.14".

changePi("xpix") → "x3.14x"
changePi("pipi") → "3.143.14"
changePi("pip") → "3.14p"

Java :
1
2
3
4
5
6
7
public String changePi(String str) {
  if (str.length() < 1) return "";
 int index = str.indexOf("pi");
 if (index < 0) return str;
 String temp = str.substring(0, index);
 return temp+"3.14"+changePi(str.substring(index+2, str.length()));
}

Test result:
C# :
1
2
3
4
5
6
7
8
9
public static String changePi(String str)
 {
            if (str.Length < 1) return "";
            int index = str.IndexOf("pi");
            if (index < 0 ) return str;
            String temp0 = str.Substring(0, index);
            String temp = str.Substring(index+2, str.Length-(2+index));
            return temp0+"3.14" + changePi(temp);
 }

Test Result :

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 :