Search code examples
javaif-statementlogical-operatorssimplification

Simplifying an if statement


I have a working solution for a problem found here. After writing it, I noticed I have the exact same statement in both parts of the if/else:

public boolean groupSum6(int start, int[] nums, int target) {
  if(start >= nums.length) return target == 0;

  int next = start + 1;
  int cur = nums[start];

  if(cur == 6) return groupSum6(next, nums, target - cur);
  return groupSum6(next, nums, target - cur) || groupSum6(next, nums, target);
}

After a little retooling, I was able to 'simplify' the problem to this:

public boolean groupSum6(int start, int[] nums, int target) {
  if(start >= nums.length) return target == 0;

  int next = start + 1;
  int cur = nums[start];

  if(cur != 6) {
      boolean success = groupSum6(next, nums, target);
      if(success) return true;
  }
  return groupSum6(next, nums, target - cur);
}

I definitely prefer the second solution, even though it is a bit more verbose. My question is, is there a way to simplify this even further? Something seems off to me about having an if statement that returns true, but I might just be over analyzing the problem. I ask solely for improving my logic simplification abilities, not because I think it is something that would be necessary to do.


Solution

  • This here is more simplified.

    public boolean groupSum6(int start, int[] nums, int target) {
      if(start >= nums.length) return target == 0;
    
      int next = start + 1;
      int cur = nums[start];
    
      boolean minusCur = groupSum6(next, nums, target - cur);
      return (cur == 6) ? minusCur : (minusCur || groupSum6(next, nums, target));
    }
    

    The lines I added will check if cur == 6 it will return minusCur and if not it will return (minusCur || groupSum6(next, nums, target)));