First of all : smells like recurision of course!
Since you also wanted to know the principle, I did my best to explain it human language. I think recursion is most of the times very easy, you only have to grasp 2 steps
- The first step
- All the other steps (with same logic)
In human language :
In short :
1. The permutation of 1 element is one element.
2. The permutation of a set of elements is a list each of the elements, concatenated with every permutation of the other elements.
Example :
If the set just have one element -->
return it.
perm(a) -> a
If the set has two characters : for
each element in it : return the
element , with the permutation of the
rest of the elements added, like so :
perm(ab) ->
a + perm(b) -> ab
b + perm(a) -> ba
Further : for each characte in set : return charachter, concatenated with perumation of > the rest of the set
perm(abc) ->
a + perm(bc) --> abc, acb
b + perm(ac) --> bac, bca
c + perm(ab) --> cab, cba
perm(abc...z) -->
a + perm(...), b + perm(....)
....
The pseudocode I found on http://www.programmersheaven.com/mb/Algorithms/369713/369713/permutation-algorithm-help/
makePermutations(permutation) {
if (length permutation < required length) {
for (i = min digit to max digit) {
if (i not in permutation) {
makePermutations(permutation+i)
}
}
} else {
add permutation to list
}
}
C#
OK, and something more elaborate (and since it is tagged c #), from http://radio.weblogs.com/0111551/stories/2002/10/14/permutations.html :
Rather lengthy, but I decided to copy it anyway, so the post is not dependent on the original.
The Function takes a string of characters, and writes down every possible permutation of that exact string, so for exaple, if "ABC" has been supplied, should spill out:
ABC, ACB, BAC, BCA, CAB, CBA.
using System;
namespace ConsoleApplication3
{
class Permute
{
private void swap (ref char a, ref char b)
{
if(a==b)return;
a^=b;
b^=a;
a^=b;
}
public void setper(char[] list)
{
int x=list.Length-1;
go(list,0,x);
}
private void go (char[] list, int k, int m)
{
int i;
if (k == m)
{
Console.Write (list);
Console.WriteLine (" ");
}
else
for (i = k; i <= m; i++)
{
swap (ref list[k],ref list[i]);
go (list, k+1, m);
swap (ref list[k],ref list[i]);
}
}
}
class Class1
{
static void Main()
{
Permute p = new Permute();
string c="sagiv";
char []c2=c.ToCharArray ();
/*calling the permute*/
p.setper(c2);
}
}
}