Monday, December 1, 2008

Generating Permutations

This has been a problem I always had difficulty with. The only resort I had till now was to memorize the solution and spit it out when needed. But now, with a algorithms class behind me and a little bit more insight into the problem, I can atlast cook up the logic here.

SO, the Question is:
Given n items (numbers, chars) generate/print all possible permutation of them

Algorithm:
1. Take a item i and put it in the perm array
2. Generate Permutation for rest of the n-1 elements (Print perm array when n==0)
3. Put back Item i in elements


public class Permute {
public void permute(String str){
int l=str.length();
boolean [] used=new boolean[l];
StringBuilder out=new StringBuilder();
char []in=str.toCharArray();
doPermute(in,out,used, l, 0);
}

private void doPermute(char[] in, StringBuilder out, boolean[] used, int n,
int level) {
if (level==n){
System.out.println(out.toString());
return;
}

for(int i=0;i<n;i++){
if(used[i]) continue;
out.append(in[i]);
used[i]=true;
doPermute(in, out, used, n, level+1);
used[i]=false;
out.setLength(out.length()-1);
}

}
}


References:

1. Programming Interviews Exposed
2. http://www.paulgriffiths.net/program/c/perm.php

No comments:

Related Posts with Thumbnails