多阵列的笛卡尔积

时间:2011-10-30 14:45:23

标签: arrays algorithm list multidimensional-array

我认为这基本上是一个简单的问题,但我被困住了。我的大脑被这个问题阻止了,所以我希望你能帮助我。 我有2到N个整数数组,比如

{1,2,3,4,5}
{1,2,3,4,5,6}
{1,3,5}
.....

现在我想要一个包含int [N]数组的列表,每个posibillity都像

{1,1,1}
{1,1,3}
{1,1,5}
{1,2,1}
....
{1,3,1}
....
{2,1,1}
{2,1,3}
....
{5,6,5}

所以其中有6 * 5 * 3(90)个元素。

有一个简单的算法吗?我认为语言并不重要,但我更喜欢Java。

3 个答案:

答案 0 :(得分:2)

Thx的帮助! 我在java中为下一个具有相同问题的人添加了一个有效的答案。我也是通用的,所以你可以在任何对象上有任何CartesianProduct,而不仅仅是int:

public class Product {

    @SuppressWarnings("unchecked")
    public static <T> List<T[]> getCartesianProduct(T[]... objects){
        List<T[]> ret = null;
        if (objects != null){               
            //saves length from first dimension. its the size of T[] of the returned list
            int len = objects.length;
            //saves all lengthes from second dimension
            int[] lenghtes = new int[len];
            // arrayIndex
            int array = 0;
            // saves the sum of returned T[]'s
            int lenSum = 1;
            for (T[] t: objects){
                lenSum *= t.length;
                lenghtes[array++] = t.length;
            }
            //initalize the List with the correct lenght to avoid internal array-copies
            ret = new ArrayList<T[]>(lenSum);
            //reusable class for instatiation of T[]
            Class<T> clazz = (Class<T>) objects[0][0].getClass();
            T[] tArray;
            //values stores arrayIndexes to get correct values from objects
            int[] values = new int[len];

            for (int i = 0; i < lenSum; i++){
                tArray = (T[])Array.newInstance(clazz, len);
                for (int j = 0; j < len; j++){
                    tArray[j] = objects[j][values[j]];
                }
                ret.add(tArray);
                //value counting:
                //increment first value
                values[0]++;
                for (int v = 0; v < len; v++){
                    //check if values[v] doesn't exceed array length
                    if (values[v] == lenghtes[v]){
                        //set it to null and increment the next one, if not the last
                        values[v] = 0;
                        if (v+1 < len){
                            values[v+1]++;
                        }
                    }
                }

            }
        } 
        return ret;
    }
}

答案 1 :(得分:0)

据我所知,你需要得到所有的排列。

使用递归算法,详细here

答案 2 :(得分:0)

我认为这应该可以正常工作:

concatMap(λa - &gt; concatMap(λb - &gt; concatMap(λc - >(a,b,c))L3)L2)L1

其中concatMap(在C#中称为SelectMany)定义为

concatMap f l = concat(map f l)。

并映射将函数映射到列表

和concat(有时称为flatten)获取List列表并将其转换为平面列表