用c ++打印所有安排

时间:2018-04-20 06:11:27

标签: c++ permutation

我想列出所有安排,以下是我的示例代码:

const unsigned char item1[] = {'b'};
const unsigned char item2[] = { 'A', 'C' ,'D'};
const unsigned char item3[] = {'1','2'};

int _tmain(int argc, _TCHAR* argv[])
{
    for (int i = 0; i < sizeof(item1) / sizeof(unsigned char); i++){
        for (int j = 0; j < sizeof(item2) / sizeof(unsigned char); j++){
            for (int k = 0; k < sizeof(item3) / sizeof(unsigned char); k++){
                printf("%c%c%c\n",item1[i],item2[j],item3[k]);
            }
        }
    }
    return 0;
}

这将打印所有排列,但我担心如果数组项是从item1item99,代码很难维护。是否有更好的解决方案来打印所有安排?谢谢!

2 个答案:

答案 0 :(得分:2)

您可以将“迭代器”存储在矢量中,然后您可以执行以下操作:

bool increase(const std::vector<std::string>& v, std::vector<std::size_t>& it)
{
    for (std::size_t i = 0, size = it.size(); i != size; ++i) {
        const std::size_t index = size - 1 - i;
        ++it[index];
        if (it[index] == v[index].size()) {
            it[index] = 0;
        } else {
            return true;
        }
    }
    return false;
}

void do_job(const std::vector<std::string>& v, std::vector<std::size_t>& it)
{
    for (std::size_t i = 0, size = v.size(); i != size; ++i) {
        std::cout << v[i][it[i]];
    }
    std::cout << std::endl;
}

void iterate(const std::vector<std::string>& v)
{
    std::vector<std::size_t> it(v.size(), 0);

    do {
        do_job(v, it);
    } while (increase(v, it));
}

Demo

答案 1 :(得分:1)

实现此目的的一个好方法是将问题视为整数基本转换问题。因此,组合的总数是所有阵列大小的乘积。输出字符串n足以确定应在字符串中打印的数组indeces。 既然你已将它标记为C ++问题,我会使用2-D向量,因为这会让生活变得更简单:

int _tmain(int argc, _TCHAR* argv[])
{
    // Initialize the vector
    vector<vector<char>> v( 3 );

    v[0].push_back( 'b' );
    v[1].push_back( 'A' );
    v[1].push_back( 'C' );
    v[1].push_back( 'D' );
    v[2].push_back( '1' );
    v[2].push_back( '2' );

    // This is a convenience vector of sizes of each 1-D vector
    vector<size_t> sizes( v.size() );

    // Get the total number of combinations and individual vector
    // sizes
    size_t total = 1;
    for( size_t i = 0; i < v.size(); ++i )
    {
        sizes[i] = v[i].size();
        total *= sizes[i];
    }

    size_t done = 0;

    // Loop till all the combinations are printed
    while( done != total )
    {
        // Remainder, which is the index of the element
        // in the 1-D vector that is to be printed
        size_t r = 0;
        // Quotient to be used for the next remainder
        size_t q = done;
        // Combination to be printed
        string s = "";

        // Loop over the 1-D vectors, picking the correct
        // character from each
        for( size_t i = 0; i < v.size(); ++i )
        {
            r = q % sizes[v.size() - 1 - i];
            q = static_cast<size_t>( floor( q/sizes[v.size() - 1 - i] ) );
            s = v[v.size() - 1 - i][r] + s;
        }

        cout<<s<<"\n";

        done++;
    }
    return 0;
}