, , . :
package so5987154;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class Summation {
private int sum(final Integer start, final Collection<Integer> list) {
int sum = start;
for (final int i : list) {
sum += i;
}
return sum;
}
public boolean groupSum5(final int start, final int[] nums, final int target) {
final List<Integer> fixed = Lists.newArrayList();
final List<Integer> candidates = Lists.newArrayList();
for (int i = 0; i < nums.length; i++) {
final int cand = nums[i];
if (cand == 1 && i > 0) {
final int prev = nums[i - 1];
if (prev % 5 != 0) {
candidates.add(cand);
}
} else if (cand % 5 == 0) {
fixed.add(cand);
} else if (cand <= target) {
candidates.add(cand);
}
}
final int sumFixed = sum(0, fixed);
if (sumFixed == target) {
return true;
}
if (sumFixed <= target && !candidates.isEmpty()) {
final Set<Set<Integer>> powerSet = Sets.powerSet(Sets.newHashSet(candidates));
for (final Set<Integer> set : powerSet) {
if (sumFixed + sum(0, set) == target) {
return true;
}
}
}
return false;
}
}
:
package so5987154.tests;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import so5987154.Summation;
@SuppressWarnings("PMD")
public class SummationTest {
private final Summation s = new Summation();
@Test
public void testGroupSum5() {
assertTrue(s.groupSum5(0, new int[] { 2, 5, 10, 4 }, 19));
assertTrue(s.groupSum5(0, new int[] { 2, 5, 10, 4 }, 17));
assertFalse(s.groupSum5(0, new int[] { 2, 5, 10, 4 }, 12));
assertTrue(s.groupSum5(0, new int[] { 2, 5, 10, 4 }, 19));
assertTrue(s.groupSum5(0, new int[] { 3, 5, 1 }, 5));
assertFalse(s.groupSum5(0, new int[] { 3, 5, 1 }, 4));
assertTrue(s.groupSum5(0, new int[] { 3, 1 }, 4));
assertFalse(s.groupSum5(0, new int[] { 3, 1 }, 2));
assertTrue(s.groupSum5(0, new int[] { 1 }, 1));
}
}
, start - . ints:
int.
:
- test, start = > return true
- test, start is over target = > return false
- test, = > return false
- start + x, x - x = > return OR
: {2, 5, 10, 4}, target = 19
5: 5 + 10 = 15, 1, 5 = > {2, 4}
: method(15, {2, 4}, 19)
- start == target = > NO
- start > target = > NO
- array empty = > NO
- r1 = (15 + 2, {4}, 19) r2 = (15 + 4, {2}, 19)
(r1): method(15+2, {4}, 19)
- start == target = > NO
- start > target = > NO
- array empty = > NO
- r11 = (15 + 2 + 4, {}, 19)
(r11): method(15+2+4, {}, 19)
- start == target = > NO
- start > target = > YES = > false
(r2): method(15+4, {2}, 19)
- start == target = > YES = > true
r1 = r11 = false r2 = true = > return false OR true = true, END
, Sets.powerSet r (k)