Question

I'm trying to solve the following problem in Java:

I have a list of 12 'Person' objects (but let's represent them by integers to simplify calculations) of which I want to create all possible unique combinations. I found enough snippets online to help me with that (I used this one so far), but here's the part I can 't figure out:

The list is divided in 4 sublists of variable length in which the order should not matter. These lengths are defined in an int array, e.g. {3,4,2,3}.

In the given example the original list could look like this:

{ 1,2,3, 4,5,6,7, 8,9, 10,11,12 }

Where this one would be the same so it should not be calculated:

{ 3,2,1, 7,6,5,4, 9,8, 12,11,10 }

I only want to calculate one because first calculating every combination and then sorting all sublists to then compare all lists would of course be very unperformant.

PS: I could'nt find a better title than this, which is why I didn't succeed at googling the problem either. Suggestions would be appreciated :-)

Was it helpful?

Solution

I spent some time on it and wrote some code using a library for combinations https://code.google.com/p/combinatoricslib/#3._Simple_combinations

It prints out the combinations you need. I hope it helps.

public class Test {

    static List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
    static int[] groups = new int[] { 3, 4, 2, 3 };

    public static void main(String[] args) throws Exception {
        print("", 0, list);
    }

    private static void print(String previousVector, int groupIndex, List<Integer> aList) {
        if (groupIndex == groups.length) { // last group
            System.out.println(previousVector);
            return;
        }

        ICombinatoricsVector<Integer> vector = Factory.createVector(aList.toArray(new Integer[0]));
        Generator<Integer> generator = Factory.createSimpleCombinationGenerator(vector, groups[groupIndex]);

        for (ICombinatoricsVector<Integer> combination : generator) {
            String vectorString = previousVector + combination.getVector().toString();
            List<Integer> copy = new LinkedList<>(aList);
            copy.removeAll(combination.getVector());
            print(vectorString, groupIndex + 1, copy); 
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top