I need to get all possible combinations of 5 objects from set of 7 objects. Combinations without repetition (the order of selection does not matter, that's the same objects selected in different orders are regarded as the same combination).
I have implementation, it works properly and produces the correct result:
String[] vegetablesSet = {"Pepper", "Cabbage", "Tomato", "Carrot", "Beans", "Cucumber", "Peas"};
final int SALAD_COMBINATION_SIZE = 5; // Example: {"Tomato", "Cabbage", "Cucumber", "Pepper", "Carrot"}
Set<Set<String>> allSaladCombinations = new HashSet<>();
for (int i = 1, max = 1 << vegetablesSet.length; i < max; i++) {
Set<String> set = new HashSet<>();
int count = 0;
for (int j = 0, k = 1; j < vegetablesSet.length; j++, k <<= 1) {
if ((k & i) != 0) {
set.add(vegetablesSet[j]);
count++;
}
}
if (count == SALAD_COMBINATION_SIZE) {
allSaladCombinations.add(set);
}
}
for (Set<String> set : allSaladCombinations) {
for (String vegatable : set) {
System.out.print(vegatable + " ");
}
System.out.println();
}
Output is correct: 21 right combinations has been found.
But it uses a bitwise operators and in my assessment it's not very readable, maintainable and extensible. I'd like to refactor or completely rewrite it to a more flexible and understandable object oriented approach. I'm very interested in how this could be done using OOP and recursion.
I do not use in my project Google Guava
, Apache Commons
or CombinatoricsLib
. And I'd not want to include the whole third-party library for only one method. I was searching on the site for similar issues, but have found only good clear permutation implementation: https://stackoverflow.com/a/14486955
These cases have a somewhat similar meaning, but order of objects does not matter for me, in my case they're considered the same combinations and should not be calculated.