I have an array of unique strings from which i need to create all possible arrays with the same length.
String[] str = {"Belgium", "France", "Germany"};
The goal is to create a list of arrays which have every possible value from above array at each index,
[Belgium, Belgium, Belgium]
[Belgium, Belgium, France]
[Belgium, Belgium, Germany]
[Belgium, France, Belgium]
[Belgium, France, France]
[Belgium, France, Germany]
[Belgium, Germany, Belgium]
[Belgium, Germany, France]
[Belgium, Germany, Germany]
[France, Belgium, Belgium]
....
[Germany, Germany, France]
[Germany, Germany, Germany]
My code to create this looks like
static List<String[]> getAllAllocations(String[] input){
List<String[]> result = new ArrayList<>();
if(input.length == 2){
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
result.add(new String[]{input[i], input[j]});
}
}
}
else if(input.length == 3){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
for(int k = 0; k < 3; k++){
result.add(new String[]{input[i], input[j], input[k]});
}
}
}
}
else if(input.length == 4){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 4; k++){
for(int m = 0; m < 4; m++){
result.add(new String[]{input[i], input[j], input[k], input[m]});
}
}
}
}
}
//else if(input.length == 5) similar code with 5 for loops
//else if(input.length == 6) similar code with 6 for loops
//else if(input.length == 7) similar code with 7 for loops
//else if(input.length == 8) similar code with 8 for loops
return result;
}
The array will have a variable length between 2 and 8. How can I dynamicaly create the for loops instead of chaining the if-else checks or any other way to do this in an elganter way than I did above?