我怎样才能找到所有包含1元的从一个可变数目的可变长度的阵列的排列? [英] How can I find all of the permutations consisting of 1 element from a variable number of arrays of variable length?

查看:131
本文介绍了我怎样才能找到所有包含1元的从一个可变数目的可变长度的阵列的排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 U 阵列 D 是长短不一的。我需要能够返回数组索引的所有排列,将选择不同的排列由来自每套1元。我还要求该alorithm被重新presented作为一个对象,它仅记住最后排列,并返回下一个排列用get_next方法

I have an array U of arrays D that vary in length. I need to be able to return all permutations of array indices that would select a different permutation consisting of 1 element from each set. I also require that this alorithm gets represented as an object that only remembers the last permutation, and returns the next permutation with a get_next method.

例如, U = [array_of_size_n1,array_of_size_n2,array_of_size_n3] 会有 N1 * N2 * N3 排列,每个 3 元素长。

For instance, U = [array_of_size_n1, array_of_size_n2, array_of_size_n3] There would be n1*n2*n3 permutations, each 3 elements long.

编辑:的组数也各不相同。

推荐答案

如果您使用的是蟒蛇,这是标准库的一部分: itertools.product 。但是,假设你没有,这里是一个伪code版本。

If you're using python, this is part of the standard library: itertools.product. But assuming you're not, here's a pseudocode version.

// Create an initialised array of indexes.
int[] index0(arrays) {
    // We require all arrays to be non-empty.
    for a in arrays {
        assert len(a) != 0;
    }
    return new int[len(arrays)];
}

// Increment the indices. Returns false when the indices wrap round to the start.
bool next_index(indices, arrays) {
    for (i = len(indices) - 1; i >= 0; --i) {
        indices[i] += 1
        if indices[i] < len(arrays[i]) {
            return true;
        }
        indices[i] = 0;
    }
    return false;
}

您可以使用它像这样(假设没有你的阵列是空的)。这个例子打印出的数组元素的每个组合。

You can use it like this (assuming none of your arrays are empty). This example prints out every combination of elements from the arrays.

indices = index0(arrays); 
{
    for (i = 0; i < len(arrays); ++i) {
        print arrays[i][indices[i]];
    }
    print
} while next_index(indices);

这篇关于我怎样才能找到所有包含1元的从一个可变数目的可变长度的阵列的排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆