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:


No comments:

Post a Comment