geek-o-pedia

Everything Geek !

Efficient String Permutation Program.

with 2 comments

The following piece of a code is a very efficient use of recursion to find the possible permutation of a string.


public class Permutations {

   public  static void perm1(String s) { perm1("", s); }

   private static void perm1(String prefix, String s) {
        int N = s.length();
        if (N == 0)
            System.out.println(prefix);
        else {
            for(int i = 0; i < N; i++){
               perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
            }
        }
    }
    public static void main(String[] args) {
       String alphabet = "Test";
       String elements = alphabet.substring(0, alphabet.length());
       perm1(elements);
    }
}

Debugging this code might prove to be a little difficult though but excellent logic though.

Technorati Tags: , ,

Written by the-geek

July 23, 2007 at 5:56 pm

Posted in java

2 Responses

Subscribe to comments with RSS.

  1. Nice! This is exactly what i was looking for. I may have to borrow it for a fun personal project, may I?

    jordan

    July 6, 2009 at 1:27 am

  2. Awesome coding….
    Can you let me know how you could arrive at this solution….

    praneeth

    August 12, 2009 at 7:25 pm


Leave a Reply