Wednesday, June 15, 2016

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:


array6 - Recursive - Java & C#

Given an array of ints, compute recursively if the array contains a 6. 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.

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

Test Result:


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

            //Main recursive process
            int[] temp = new int[nums.Length-index-1];
            System.Array.Copy(nums,index+1,temp,0,temp.Length);
            return array6(temp, index);
        }

Test Result: