Is there an efficient way to find all possible combinations between multiple enums in Java?
Consider the following three enums -
public enum EnumOne {
One ("One"),
OneMore ("OneMore");
}
public enum EnumTwo {
Two ("Two"),
}
public enum EnumThree {
Three ("Three"),
ThreeMore ("ThreeMore");
}
I would like the output to produce all possible combinations between these multiple enums i.e.
{EnumOne.One, EnumTwo.Two, EnumThree.Three},
{EnumOne.One, EnumTwo.Two, EnumThree.ThreeMore},
{EnumOne.OneMore, EnumTwo.Two, EnumThree.Three},
{EnumOne.OneMore, EnumTwo.Two, EnumThree.ThreeMore}
Hoping to find an effective way of handling it.
Thanks
the complexity of the algorithms is O(NxMxK .... xZ) if I'm wrong, I don't know if it an "efficient way" .... I use as a backtraking solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ProductEnums {
public enum EnumOne {
One,
OneMore;
}
public enum EnumTwo {
Two,
}
public enum EnumThree {
Three,
ThreeMore;
}
public static void main(String[] args) {
// pass each values in enums
List a = product(EnumOne.values(),
EnumTwo.values(), EnumThree.values());
System.out.println(a);
}
public static List<List<Enum>> product(Enum[]... enums) {
return product(new ArrayList<>(Arrays.asList(enums)));
}
public static List<List<Enum>> product(List<Enum[]> enums) {
if (enums.isEmpty()) {
//Trivial case of recursive function
return new ArrayList<>();
}
//remove first element
Enum[] myEnums = enums.remove(0);
List<List<Enum>> out = new ArrayList<>();
for (Enum e : myEnums) {
//call recursive
List<List<Enum>> list = product(enums);
for (List<Enum> list_enum : list) {
//for each list get from recursion adding element e
list_enum.add(0, e);
out.add(list_enum);
}
if(list.isEmpty()){
List<Enum> list_enum = new ArrayList<>();
list_enum.add(e);
out.add(list_enum);
}
}
enums.add(0, myEnums); //Backtraking
return out;
}
}
Result
[[One, Two, Three], [One, Two, ThreeMore], [OneMore, Two, Three], [OneMore, Two, ThreeMore]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With