Wednesday, June 15, 2016

allStar - Recursive - Java & C#

Given a string, compute recursively a new string where all the adjacent chars are now separated by a "*".

allStar("hello") → "h*e*l*l*o"
allStar("abc") → "a*b*c"
allStar("ab") → "a*b"
Java :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public static String allStar(String str)
 {
  //Stop Condition
  if(str.length()<1) return "";
  if(str.length() == 1) return str+"*";
  
  
  //Main recursive process
  return str.charAt(0)+"*"+allStar(str.substring(1));
 }

Hasil :

C# :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
   public static string allStar(String str)
        { 
            //Kondisi stop
            if (str.Length < 1) return "";
            if (str.Length == 1) return str;


            //Proses rekursif
            return str[0] + "*" + allStar(str.Substring(1));
        }

Hasil :

array11 - Recursive - Java & C#

Given an array of ints, compute recursively the number of times that the value 11 appears in the array. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.

array11([1, 2, 11], 0) → 1
array11([11, 11], 0) → 2
array11([1, 2, 3, 4], 0) → 0

Java :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public static int array11(int[] nums, int index)
 {
  //Stop Condition
  if(nums.length == 0 ) return 0;
  if(nums.length == 1)
  {
   if(nums[0] == 11) return 1;
   else return 0;
  }
  
  //Main recursive process
  int[] temp = Arrays.copyOfRange(nums, index+1, nums.length);
  if(nums[index] == 11) return 1+array11(temp,index);
  else return array11(temp,index);
 }
 

Test Result :

C# :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 public static int array11(int[] nums, int index)
        { 
            //Kondisi stop
            if (nums.Length == 0) return 0;
            if (nums.Length == 1)
            {
                if (nums[0] == 11) return 1;
                else return 0;
            }

            //Proses rekursif
            int[] temp = new int[nums.Length - index - 1];
            System.Array.Copy(nums, index+1, temp, 0, temp.Length);
            if (nums[index] == 11) return 1 + array11(temp, index);
            else return array11(temp, index);
        }

Test Result: