Recently i implemented code for below Suppose I have 2 arrays as -
arr1 = [a,b,c]
arr2 = [d,e]
and should be as
output = [ad,ae,bd,be,cd,ce]
Now suppose I have multiple arrays.
for eg :
arr1=[a,b,c]
arr2=[d,e]
arr3=[f,g,h,i]
arrN=[x,y,z,h,o]
output = [adf..x,adf..y and so on]
How to implement this in JAVA? kindly help
My attempt :
for(int i=0;i<arr1.length();i++)
{
for(int j=0;i<arr2.length();j++)
{
System.out.print(arr1[i] + arr2[j] );
}
}
This is my attempt at getting combinations from multiple arrays(containers).
private List<List<T>> getCombination(int currentIndex, List<TempContainer<T>> containers) {
if (currentIndex == containers.size()) {
// Skip the items for the last container
List<List<T>> combinations = new ArrayList<List<T>>();
combinations.add(new ArrayList<T>());
return combinations;
}
List<List<T>> combinations = new ArrayList<List<T>>();
TempContainer<T> container = containers.get(currentIndex);
List<T> containerItemList = container.getItems();
// Get combination from next index
List<List<T>> suffixList = getCombination(currentIndex + 1, containers);
int size = containerItemList.size();
for (int ii = 0; ii < size; ii++) {
T containerItem = containerItemList.get(ii);
if (suffixList != null) {
for (List<T> suffix : suffixList) {
List<T> nextCombination = new ArrayList<T>();
nextCombination.add(containerItem);
nextCombination.addAll(suffix);
combinations.add(nextCombination);
}
}
}
return combinations;
}
The method takes a list of containers with items. e.g. Container 1 will have [a,b] and Container 2 will have [c,d,e]. The method can take any number of containers. // The container class is declared as follows:
public class TempContainer<T> {
private List<T> items;
public void setItems(List<T> items) {
this.items = items;
}
public List<T> getItems() {
return items;
}
}
Call this method as follows:
List<String> list1 = new ArrayList<String>();
list1.add("1");
list1.add("2");
List<String> list2 = new ArrayList<String>();
list2.add("3");
list2.add("4");
list2.add("5");
TempContainer container1 = new TempContainer();
container1.setItems(list1);
TempContainer container2 = new TempContainer();
container2.setItems(list2);
List<TempContainer> containers = new ArrayList<TempContainer>(2);
containers.add(container1);
containers.add(container2);
// Get combinations
List<List<T>> combinations = getCombination(0, containers);
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