Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

How to generate array-list of all combinations of a table in C/C++

I want to make automated measurements varying several parameters. There is a table with variable row/column-number containing parameter values, e.g.:

a1 b1 c1
a2 b2 c2
a3 b3 c3

Is there an easy was for generating list of Arrays containing all combinations in column direction like that:

a1 a2 a3
b1 a2 a3
c1 a2 a3
a1 b2 a3
b1 b2 a3
...
c1 c2 c3

3x3 Table should result in 27 combinations (3!).

The algorthm should be if possible in C/C++, STL/Qt would be also great.

Thank you for any hint!

P.S.: It looks easy, but I have sat on this problem since 2 hours already! :-(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use recursion:

int selection[rows]; // Stores which item is selected for each row

void func(int row_num) {
    if (row_num == rows) { // If we've selected for all the rows
        // Do your thing with selection[]
        return;
    }

    for (int i = 0; i < columns; i++) { // For each possible selection you can make row_num
        selection[row_num] = i; // Choose it
        func(row_num + 1); // Recurse over all possible combinations for the remaining rows
    } 
}

func(0); // Goes over all possibilities

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...