I have found this code the internet to computer all possible Permutations for a given Vector ..
import java.util.Vector;
class Permute {
static int count = 0;
public static void permute(Vector unvisited, Vector visited) {
if ( unvisited.isEmpty() ) {
System.out.println("Permutation: "+visited);
count++;
}
else {
//System.out.println("Trace: "+visited+" "+unvisited);
int l = unvisited.size();
for(int i = 0; i<l; i++) {
String next = String.valueOf(unvisited.remove(i));
visited.add(next);
permute(unvisited,visited);
unvisited.add(i,next);
visited.remove(next);
}
}
}
public static void main(String[] args) {
Vector objects = new Vector();
objects.add(1);
objects.add(5);
objects.add(8);
permute(objects, new Vector() );
System.out.println(count+" Permutationen gefunden");
}
}
Bu I have a small problem in understanding the code and the flow of the instructions .
What I misses is when these two lines are called
unvisited.add(i,next);
visited.remove(next);
As I see there is a recursion permute(..) function before reaching them !
First try to understand what the permute() function does. It juggles two vectors: unvisited and visited. In the execution of permute(), the function will take an element from unvisited and move it to visited. Think of it as “building” a permutation.
For example:
we move an element from unvisited to visited
Now to build the rest of the permutations that start with 1, we need to find the permutations of unvisited, or {5,8}. So we recursively call permute() to find the rest.
So what does
do ?
As each permutation is being built, the function is modifying a unified/common/shared source of data: the vectors. They are constantly being modified as elements are shifted from unvisited to visited. However, we need to reset these vectors to find the rest of the permutations. In the example above, we need to put 1 back to unvisited find the permutations that start with 5, or 8. So we:
and