Rearrange Array Elements

How do I get a combination from an array of counter lines 2? Those..

List<string> myString = {"a", "b", "c", "d", "f"};

The permutation will look like this:

ab ac ad af ba bc bd bf ca cb cd cf etc...

I do not know how to start this algorithm. If this helps, I would rather do a loop than recursion, because in my real implementation I need to assign a value to the permutation elements and compare them with each other and choose the highest one.

+3
source share
4 answers

Using Linq:

var result = 
    from a in myString
    from b in myString
    where a != b
    select a + b;
+6
source

Do not use LINQ

List<string> myString = {"a", "b", "c", "d", "f"};
List<String> result = new List<String> ();
for (int i = 0; i < myString.Count; i++)
{
    for (int j = 0; j < myString.Count; j++)
    {
        if (i == j)
            continue;
        result.Add(myString[i] + myString[j]);
    }
}
+4
source

LINQ :

var permutations = new List<string>();
for(int i = 0; i < myString.Count; i++) 
{
    for(int j = 0; j < myString.Count; j++)
    {
        if(i == j)
            continue;

        var permutation = string.Format("{0}{1}", myString[i], myString[j]);
        permutations.Add(permutation);
    }
}
+1

:

        string[] arreglo = new string[6];
        arreglo[0] = "a";
        arreglo[1] = "b";
        arreglo[2] = "c";
        arreglo[3] = "d";
        arreglo[4] = "e";
        arreglo[5] = "f";

        var permutations = new List<string>();
        for (int i = 0; i < arreglo.Length; i++)
        {
            for (int j = 0; j < arreglo.Length; j++)
            {
                for (int k = 0; k < arreglo.Length; k++)
                {
                    for (int l = 0; l < arreglo.Length; l++)
                    {
                        for (int m = 0; m < arreglo.Length; m++)
                        {
                            for (int n = 0; n < arreglo.Length; n++)
                            {
                                if (i ==j ||j == k||i == k||k == l||i == l||j == l||i == m||j == m||k == m||l == m||i == n||j == n||k == n||l == n||m == n)
                                    continue;

                                var permutation = string.Format("{0}{1}{2}{3}{4}{5}", arreglo[i], arreglo[j], arreglo[k], arreglo[l], arreglo[m],arreglo[n]);
                                permutations.Add(permutation);
                            }
                        }
                    }
                }
            }
        }

        foreach(var element in permutations)
        {
            Console.WriteLine(element);
        }
        Console.ReadLine();
0

Source: https://habr.com/ru/post/1784280/


All Articles