Java – find all possible enum combinations
•
Java
Is there an effective way to find all possible combinations between multiple enumerations in Java?
Consider the following three enumerations –
public enum EnumOne {
One ("One"),OneMore ("OneMore");
}
public enum EnumTwo {
Two ("Two"),}
public enum EnumThree {
Three ("Three"),ThreeMore ("ThreeMore");
}
I want the output to produce all possible combinations between these multiple enumerations, that is
{EnumOne.One,EnumTwo.Two,EnumThree.Three},{EnumOne.One,EnumThree.ThreeMore},{EnumOne.OneMore,EnumThree.ThreeMore}
I hope to find an effective way to deal with it
thank you
Solution
The complexity of the algorithm is O (nxmxk.... XZ). If I am wrong, I don't know whether it is an "effective way" I use it as a backtracking 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
