java - How recursion works in a code for computing Permutations of a number -
i have found code internet computer possible permutations 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 = 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 have small problem in understanding code , flow of instructions . misses when these 2 lines called
unvisited.add(i,next); visited.remove(next);
as see there recursion permute(..)
function before reaching them !
first try understand permute() function does. juggles 2 vectors: unvisited , visited. in execution of permute(), function take element unvisited , move visited. think of "building" permutation.
for example:
unvisited: 1, 5, 8 visited:
we move element unvisited visited
unvisited: 5, 8 visited: 1
now build rest of permutations start 1, need find permutations of unvisited, or {5,8}. recursively call permute() find rest.
so does
unvisited.add(i,next); visited.remove(next);
do ?
as each permutation being built, function modifying unified/common/shared source of data: vectors. being modified elements shifted unvisited visited. however, need reset these vectors find rest of permutations. in example above, need put 1 back unvisited find permutations start 5, or 8. we:
unvisited.add(i,next); //add unvisited in original position
and
visited.remove(next); //remove visited.
Comments
Post a Comment