views:

235

answers:

5

Hello friends, I have an arraylist which contains some objects and i have to get permutation of that objects?How can i do that? Suppose MyList is an arraylist which contains 4 objects.

ArrayList myList = new ArrayList();
myList.Add(1);
myList.Add(2);
myList.Add(3);
myList.Add(4);

so arraylist count is 4 so i want 4!=24 I want 24 permutations of that objects. How can i do That in C#.Please help me.

Thanks in advance.

A: 

You can do this with lovely lovely recursion.

The base case: the permutation of an array of size 1 being the array itself.

The recursive case: the permutation of the array of size n being, each permutation of size (n - 1) with the nth item added at each possible position.

Does that make sense?

Tom Duckering
A: 

May be like this, not tested though.

public static IEnumerable<string> permute(string s){
    if (s.Count() > 1)
        return from c in s
               from p in permute(s.Remove(s.IndexOf(c), 1))
               select string.Format("{0}{1}", c, p);
    else
        return new string[] { s };
}
S.Mark
A: 

This Stanford lecture from the class "Programming Abstractions" explains a recursive solution really well.

http://www.youtube.com/watch?v=uFJhEPrbycQ#t=37m25s

Anurag
A: 

Here is a nice article going in depth of C++ implementation of next_permutation. Yes, it's in C++ but the syntax is not much different, and explanation is good enough. Cheers.

MadH
maybe link will help :P
Anurag
can't find that link anymore. That one seems to be a good one as well though: http://wordaligned.org/articles/next-permutation
MadH
A: 

Take a look into this library: Permutations, Combinations, and Variations using C# Generics

Rubens Farias