Created
March 10, 2015 03:54
-
-
Save sshark/6a7d38f692649c9ab624 to your computer and use it in GitHub Desktop.
List combinations with the sum of zero
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.test.sample; | |
| import java.util.Arrays; | |
| import java.util.Collections; | |
| import java.util.LinkedList; | |
| import java.util.List; | |
| public class FindZeroSumCombi { | |
| public static void main(String[] args) { | |
| Integer[] value = { -15, 10, 4, -3, 5, -7, 1, -5 }; | |
| List<List<Integer>> listInteger = new LinkedList<List<Integer>>(); | |
| for (int i = 1; i <= value.length; i++) { | |
| listInteger.addAll(populateCombinationList(Arrays.asList(value), i)); | |
| } | |
| populateZero(listInteger); | |
| } | |
| public static <T> List<List<T>> populateCombinationList(List<T> values,int size) { | |
| if (size == 0) { | |
| return Collections.singletonList(Collections.<T> emptyList()); | |
| } | |
| if (values.isEmpty()) { | |
| return Collections.emptyList(); | |
| } | |
| List<List<T>> combination = new LinkedList<List<T>>(); | |
| T iteratorValue = values.iterator().next(); | |
| List<T> subSet = new LinkedList<T>(values); | |
| subSet.remove(iteratorValue); | |
| List<List<T>> subSetCombinationList = populateCombinationList(subSet,size - 1); | |
| for (List<T> list : subSetCombinationList) { | |
| List<T> newSetList = new LinkedList<T>(list); | |
| newSetList.add(0, iteratorValue); | |
| combination.add(newSetList); | |
| } | |
| combination.addAll(populateCombinationList(subSet, size)); | |
| return combination; | |
| } | |
| public static void populateZero(List<List<Integer>> list) { | |
| for (int j = 0; j < list.size(); j++) { | |
| List<Integer> integers = list.get(j); | |
| int a = 0; | |
| for (int i = 0; i < integers.size(); i++) { | |
| a = a + integers.get(i); | |
| } | |
| if (a == 0) { | |
| System.out.println(integers + "= 0 "); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment