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 :

No comments:

Post a Comment