简体   繁体   中英

How to combine elements of a matrix without using the same row more than once each time

My goal is to combine those elements (Each letter stands for a different string)

A;B;F;...
X;C;D;...
P;O;K;...
...

in a textbox in every possible way without repetition and without combining elements of the same row. Dots represent continuation. So if the Matrix was just

A;B
X;C

The result should be AX AC BX BC. If it was

A;B;F
X;C;D
P;O;K

The result would be AXP AXO AXK ACP ACO ACK ADP ADO ADK BXP ....

I found an algorithm

private void buildAllCombinationsRecursive<TSource>(IList<TSource> i_targetList, IList<TSource> i_sourceList, int i_currentPos)
{
    if (i_currentPos == i_targetList.Count)
    {
        string combination = "";
        for (int i = 0; i < i_targetList.Count; i++)
        {
            combination += i_targetList[i] + " ";
        }

        Console.WriteLine(combination);
        return;
    }
    for (int i = 0; i < i_sourceList.Count; i++)
    {
        i_targetList[i_currentPos] = i_sourceList[i];
        this.buildAllCombinationsRecursive(i_targetList, i_sourceList, i_currentPos + 1);
    }
}

But it creates a ABC CBA etc, that I don't need.

Check out Eric Lippert's C# Cartesian product Recursion .

Each one of your 'matrix' lines will be a sequence in a recursion step.

The accumulator function will be string concatenation. Even though, for performance sake you could go for StringBuilder.Append .

Example on rextester

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM