本文介绍了多个数组元素的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在下面实现了代码假设我有2个数组-

Recently i implemented code for belowSuppose I have 2 arrays as -

arr1 = [a,b,c]

arr2 = [d,e]

,并且应为

output = [ad,ae,bd,be,cd,ce]

现在假设我有多个数组.

Now suppose I have multiple arrays.

例如:

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]

如何在JAVA中实现此功能?友善的帮助

How to implement this in JAVA? kindly help

我的尝试:

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;
}

该方法获取包含项目的容器列表.例如容器1将具有[a,b],容器2将具有[c,d,e].该方法可以使用任意数量的容器. //容器类声明如下:

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);

这篇关于多个数组元素的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 18:57