Last active
August 29, 2015 14:01
-
-
Save sshark/c7c51e75699cd6bc052f to your computer and use it in GitHub Desktop.
Find all the combinations of a given elements list using both for-loop and recursion.
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
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.List; | |
| /** | |
| * | |
| * Add VM option -ea to enable assertion. | |
| * | |
| * @author Lim, Teck Hooi | |
| * | |
| * | |
| */ | |
| public class Combinations { | |
| public static void main(String[] args) { | |
| List<Integer> numbers = Arrays.asList(new Integer[] {-15, 10, 4, -3, 5, -7, 1, -5}); | |
| List<List<Integer>> combi = combinations(numbers); | |
| System.out.println(combi.size()); | |
| for (List<Integer> l : combi) { | |
| System.out.println(l); | |
| } | |
| assert(combi.size() == 1 << numbers.size()); | |
| List<List<Integer>> forCombi = forCombinations(numbers); | |
| assert(forCombi.size() == combi.size()); | |
| for (List<Integer> eachForCombi : forCombi) { | |
| assert(combi.contains(eachForCombi)); | |
| } | |
| } | |
| static public <A> List<List<A>> forCombinations(List<A> elements) { | |
| List<List<A>> results = new ArrayList<>(); | |
| results.add(new ArrayList<A>()); | |
| for (A element : elements) { | |
| List<List<A>> tempResults = new ArrayList<>(); | |
| for (List<A> prevResult : results) { | |
| List<A> newResult = new ArrayList<>(prevResult); | |
| newResult.add(element); | |
| tempResults.add(newResult); | |
| } | |
| results.addAll(tempResults); | |
| } | |
| return results; | |
| } | |
| static public <A> List<List<A>> combinations(List<A> elements) { | |
| if (elements == null || elements.isEmpty()) { | |
| return new ArrayList<>(); | |
| } | |
| List<List<A>> results = new ArrayList<>(); | |
| results.add(new ArrayList<A>()); | |
| return _combinations(elements, results); | |
| } | |
| static private <A> List<List<A>> _combinations(List<A> elements, List<List<A>> results) { | |
| if (elements.isEmpty()) { | |
| return results; | |
| } | |
| List<List<A>> localResults = new ArrayList<>(); | |
| for (List<A> result : results) { | |
| List<A> localSeq = new ArrayList<>(result); | |
| localSeq.add(elements.get(0)); | |
| localResults.add(localSeq); | |
| } | |
| results.addAll(localResults); | |
| return _combinations(tail(elements), results); | |
| } | |
| static private <A> List<A> tail(List<A> elements) { | |
| if (elements.isEmpty() || elements.size() == 1) { | |
| return new ArrayList<>(); | |
| } | |
| return elements.subList(1, elements.size()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment