Permutation of an arraylist objects
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 array开发者_运维问答list 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!
This Stanford lecture from the class "Programming Abstractions" explains a recursive solution really well.
http://www.youtube.com/watch?v=uFJhEPrbycQ#t=37m25s
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 };
}
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.
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?
Take a look into this library: Permutations, Combinations, and Variations using C# Generics
精彩评论