Java > Recursion-2 > splitOdd10 (CodingBat Solution)

Problem:

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


Solution:

public boolean splitOdd10(int[] nums) {
  int index = 0;
  int sum1 = 0;
  int sum2 = 0;
  return recArray(nums, index, sum1, sum2);
}

private boolean recArray ( int[] nums, int index, int sum1, int sum2 ) {
  if ( index >= nums.length ) {
    return (sum1%10 == 0 && sum2%2 !=0) || (sum2%10 == 0 && sum1%2 !=0);
  }

  int value = nums[index];

  return (recArray(nums, index + 1, sum1 + value, sum2) || 
    recArray(nums, index + 1, sum1, sum2 + value));
}


4 comments :

  1. public boolean splitOdd10(int[] nums) {
      return groupSum(0,nums,0,0);
    }
    private boolean groupSum(int start,int[] nums,int sum1,int sum2) {
      if (start >= nums.length) return (sum1%10==0 & sum2%2==1)|(sum1%2==1 & sum2%10==0);
      if (groupSum(start+1,nums,sum1+nums[start],sum2)) return true;
      if (groupSum(start+1,nums,sum1,sum2+nums[start])) return true;
      return false;
    }

    ReplyDelete
  2. public boolean splitOdd10(int[] nums) {

    return helper(0,nums,0,0) ;
    }

    public boolean helper(int start, int[] nums, int sum1, int sum2){
    if(start == nums.length)
    return sum1 % 10 == 0 && sum2 % 2 == 1 ||
    sum2 % 10 == 0 && sum1 % 2 == 1;


    return helper(start + 1, nums, sum1 + nums[start], sum2) ||
    helper(start + 1, nums, sum1, sum2 + nums[start]) ;
    }

    ReplyDelete
  3. public boolean splitOdd10(int[] nums) {
    int sum = 0;
    for(int i = 0; i < nums.length; i++)
    sum += nums[i];
    return sum % 2 == 1;
    }

    ReplyDelete
    Replies
    1. But it doesn't check if sum of a group is a multiple of 10

      Delete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact