Wednesday, June 15, 2016

splitOdd10 - Recursive - Java & C#

Given an array of ints, is it possible to divide the ints into two groups, so that the sum of one group is a multiple of 10, and the sum of the other group is odd. Every int must be in one group or the other. Write a recursive helper method that takes whatever arguments you like, and make the initial call to your recursive helper from splitOdd10(). (No loops needed.)

splitOdd10([5, 5, 5]) → true
splitOdd10([5, 5, 6]) → false
splitOdd10([5, 5, 6, 1]) → true

Java :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public boolean splitOdd10(int[] nums) {
   return helper(0, nums, 0);
}

public boolean helper(int index, int[] nums, int result)
  { 
    if(index >= nums.length)
      {
        if ((result % 10) % 2 == 1) return true;
        else return false;
      }

    return helper(index + 1, nums, result + nums[index]);
  }

Test Result:

C#:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public static Boolean splitOdd10(int[] nums)
        {
            return helper(0, nums, 0);
        }

public static Boolean helper(int index, int[] nums, int result)
        { 
            if(index >= nums.Length)
            {
                if ((result % 10) % 2 == 1) return true;
                else return false;
            }

            return helper(index + 1, nums, result + nums[index]);
        }

Test :

stringClean - Recursive - Java & C#

Given a string, return recursively a "cleaned" string where adjacent chars that are the same have been reduced to a single char. So "yyzzza" yields "yza".

stringClean("yyzzza") → "yza"
stringClean("abbbcdd") → "abcd"
stringClean("Hello") → "Helo"

Java :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public String stringClean(String str) {
  //Stop Condition
  if(str.length()<2) return str;
  
  //Main recursive process
  int index = 0;
  for(index=0; index+1<str.length(); index++)
  {
    if(str.charAt(index) != str.charAt(index+1)) break;
  }
  return str.charAt(index)+stringClean(str.substring(index+1));
}

Test Result:

C#:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 public static string stringClean(string str)
        { 
            //kondisi setop
            if (str.Length < 2) return str;

            //main rekursif
            int index = 0;
            for (index=0; index+1 < str.Length; index++)
            {
                if (str[index] != str[index + 1]) break;
            }

            return str[index] + stringClean(str.Substring(index+1));

        }

Test Result :