Java > Recursion-2 > split53 (CodingBat Solution)

Problem:

Given an array of ints, is it possible to divide the ints into two groups, so that the sum of the two groups is the same, with these constraints: all the values that are multiple of 5 must be in one group, and all the values that are a multiple of 3 (and not a multiple of 5) must be in the other. (No loops needed.)

split53({1,1}) → true
split53({1, 1, 1}) → false
split53({2, 4, 2}) → true


Solution:

public boolean split53(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 == sum2;
  }

  int value = nums[index];

  if (value%5 == 0)
    return recArray(nums, index + 1, sum1 + value, sum2);
  else if (value%3 == 0)
    return recArray(nums, index + 1, sum1, sum2 + value);
  else     
    return (recArray(nums, index + 1, sum1 + value, sum2) || 
      recArray(nums, index + 1, sum1, sum2 + value));
}


2 comments :

  1. public boolean split53(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==sum2;
       if (nums[start]%5!=0 &
           groupSum(start+1,nums,sum1+nums[start],sum2))
         return true;
       if (nums[start]%3!=0 &
           groupSum(start+1,nums,sum1,sum2+nums[start]))
         return true;
       return false;
    }

    ReplyDelete
  2. public boolean split53(int[] nums) {
    final int index = 0;
    final int sum1 = 0;
    final 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 == sum2);
    }
    if (nums[index] % 5 == 0) {
    return recArray(nums, index + 1, sum1 + nums[index], sum2);
    }
    if (nums[index] % 3 == 0) {
    return recArray(nums, index + 1, sum1, nums[index] + sum2);
    }
    return recArray(nums, index + 1, sum1 + nums[index], sum2)
    || recArray(nums, index + 1, sum1, nums[index] + sum2);
    }

    ReplyDelete

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