anurag wrote:
> write a function to print all permutations of a string.can anyone
> please help me

Here is a generic program (written in Java) which does this for a
collection of objects. You can easily adapt it for a string.

import java.util.List;
import java.util.Iterator;
import java.util.Collection;
import java.util.ArrayList;

public class Permute {

   public static void main(String[] args) {

      List list = new ArrayList();

      list.add(new Integer(1));
      list.add(new Integer(2));
      list.add(new Integer(3));
      list.add(new Integer(4));

      Collection result = permute(list);

      Iterator it = result.iterator();

      int count = 1;

      while (it.hasNext()) {
         ArrayList al = (ArrayList)it.next();

         System.out.print(count+". ");

         for (int i = 0; i < al.size(); i++) {
            System.out.print(((Integer)al.get(i)).intValue()+" ");
         }

         System.out.println();

         count++;
      }

   }

   /*
     Find permutations of a list of objects
   */
   static Collection permute(List list) {

      Collection result = new ArrayList();

      if (list.size() == 1) {
         ArrayList temp = new ArrayList();
         temp.add(list.get(0));

         result.add(temp);
      }
      else if (list.size() == 2) {
         ArrayList temp1 = new ArrayList();
         temp1.add(list.get(0));
         temp1.add(list.get(1));
         ArrayList temp2 = new ArrayList();
         temp2.add(list.get(1));
         temp2.add(list.get(0));

         result.add(temp1);
         result.add(temp2);
      }
     else {
        Collection temp = permute(list.subList(1, list.size()));
        Iterator it = temp.iterator();

        while (it.hasNext()) {
          ArrayList al = (ArrayList)it.next();
          for (int i = 0; i <= al.size(); i++) {
            List x = al.subList(0, i);
            List y = al.subList(i, al.size());
            ArrayList t = new ArrayList();
            t.addAll(x);
            t.add(list.get(0));
            t.addAll(y);

            result.add(t);
          }
       }
    }

    return result;

   }

}

Regards,
Mukul


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/algogeeks
-~----------~----~----~----~------~----~------~--~---

Reply via email to