I have 5 strings, such as: "one", "two", "three", "four", and "five". I need to get all permutations of these words. I've explored all internet resources, but all solutions are so bulky and it's hard for me to understand it and integrate it to my program.
So, maybe you know any easy solution how to get permutations.
For example string are 1 2 3, it would: 123, 132, 213, 231, 312, 321.
Thanx.

Recommended Answers

All 8 Replies

private static void Test()
        {
            List<string> list = new List<string>() { "A", "B", "C" };
            IList<IList<string>> perms = Permutations(list);
            foreach (IList<string> perm in perms)
            {
                foreach (string s in perm)
                {
                    Console.Write(s);
                }
                Console.WriteLine();
            }
        }

        private static IList<IList<T>> Permutations<T>(IList<T> list)
        {
            List<IList<T>> perms = new List<IList<T>>();

            if (list.Count == 0)
                return perms; // Empty list.

            int factorial = 1;
            for (int i = 2; i <= list.Count; i++)
                factorial *= i;

            for (int v = 0; v < factorial; v++)
            {
                List<T> s = new List<T>(list);                
                int k = v;
                for (int j = 2; j <= list.Count; j++)
                {
                    int other = (k % j);
                    T temp = s[j - 1];
                    s[j - 1] = s[other];
                    s[other] = temp;

                    k = k / j;
                }
                perms.Add(s);
            }

            return perms;
        }

The printout from the Test method is:
CAB
CBA
BCA
ACB
BAC
ABC

Thanx a lot, but as it turned out I need combinations without permutaion. But I'll collect your answer.

So mark this thread as answered (cause i beleive it was) and start a new one -if necessary.
Mitja

So mark this thread as answered (cause i beleive it was) and start a new one -if necessary.
Mitja

Thanx, I want to make it solved but I can't find how to do it.

There is a button "Mark as Answered" I think.

Oh, sorry I can't find it!

Just FYI Combination Generation is right here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.