-2

I am trying to get the following output using C# using loops, I want to always start from A, then create all possible paths that consist of B, C, D and E, something like the following:

A B C D E
A B C E D
A B D C E
A B D E C
A B E C D
A B E D C

A C B D E
A C B E D
A C D B E
A C D E B
A C E B D
A C E D B

A D B C E
A D B E C
A D C B E
A D C E B
A D E B C
A D E C B

A E B C D
A E B D C
A E C B D
A E C D B
A E D B C
A E D C B

I have written a sample C# code, but I am always stuck and not getting the entire string.

  • 1
    Then please show the code that you already have... – Flat Eric Mar 04 '17 at 16:38
  • You are looking at 'power sets' http://www.programminglogic.com/powerset-algorithm-in-c/ – hyankov Mar 04 '17 at 16:42
  • I assumed the letters as integers: int[] dest = new int[] { 1, 2, 3, 4 }; int h = dest.Length + 2; for (int i = 0; i < dest.Length; i++) { for(int j=0; j < h; j++) { Console.Write(dest[i]); Console.Write("\n"); } } Console.ReadLine(); – Hisham Siam Mar 04 '17 at 16:42
  • http://stackoverflow.com/questions/19890781/creating-a-power-set-of-a-sequence – hyankov Mar 04 '17 at 16:44
  • Thank you Hristo and all the guys, but it must be always consisting from all elements, I am not sure it is a power set – Hisham Siam Mar 04 '17 at 16:53
  • Can you share your CODE, then we can check. Why you stuck and not getting the entire string. – csharpbd Mar 04 '17 at 17:33

1 Answers1

1

You can check if the next loop variables are not equal to any of the previous loop variables like this:

char[] arr = { 'B', 'C', 'D', 'E' };

foreach (var b in arr)
{
    foreach (var c in arr)
        if (c != b)
            foreach (var d in arr)
                if (d != c && d != b)
                    foreach (var e in arr)
                        if (e != d && e != c && e != b)
                            Console.WriteLine(string.Concat('A', b, c, d, e));
    Console.WriteLine();
}
Slai
  • 22,144
  • 5
  • 45
  • 53