Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combinations of a set in Java

I am trying to give the unique permutations of a set, a.k.a the combinations of a set.

For example, the combinations of the set S={A,B,C} are:

SC={AB, AC, BC}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

BA isn’t valid as AB=BA, for example.

I tried using tools like the cartesian product but I realized that would be for two sets. I could maybe use it if I did the cartesian product of set S and the same set S, but I think that would be unefficient.

I am trying to obtain triplet combinations, meaning I would like to extend the previous definition to 3 elements instead of 2, which would mean that, intrapolating, I would have tried to use: if(arr[i] != arr[j] && i !=j), but this gives the permutations and not the unique ones. However, I think it is important to first understand 2-element combinations.

>Solution :

Use nested loop like this:

    String[] values = {"A", "B", "C"};
    Set<String> combinations = new HashSet<>();
    for (int i = 0; i < values.length; i++) {
        for (int j = i + 1; j < values.length; j++) {
            combinations.add(values[i] + values[j]);
        }
    }

    System.out.println(combinations); // [AB, BC, AC]

Then with recursion you can adjust it to any number of objects in combination:

public static void main(String[] args) {
    int permutationLength = 3;
    String[] values = {"A", "B", "C", "D"};
    Set<String> combinations = new HashSet<>();
    add(values, permutationLength, 0, new StringBuilder(), combinations);

    System.out.println(combinations); // [ABC, ACD, BCD, ABD]
}

private static void add(String[] allValues, int lettersToAdd, int startingFromIndex, StringBuilder currentPermutation, Set<String> permutationCollector) {
    if (lettersToAdd == 0) {
        permutationCollector.add(currentPermutation.toString());
    }
    for (int i = startingFromIndex; i < allValues.length; i++) {
        StringBuilder permutation = new StringBuilder(currentPermutation.toString());
        permutation.append(allValues[i]);
        add(allValues, lettersToAdd - 1, i + 1, permutation, permutationCollector);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading