Anagrams (Recursive)

Enter a word of any length…
CAT
TAC,ATC,TCA,CTA,ACT,CAT,
 
Enter a word of any length…
LEAN
NAEL,ANEL,NEAL,ENAL,AENL,EANL,NALE,ANLE,NLAE,LNAE,ALNE,LANE,NELA,ENLA,NLEA,LNEA,ELNA,
LENA,AELN,EALN,ALEN,LAEN,ELAN,LEAN,

 

import java.io.*;
public class Anagram
{
    public static void main() throws IOException
     {
        InputStreamReader x=new InputStreamReader(System.in);
        BufferedReader y=new BufferedReader(x);
        System.out.println(“Enter a word of any length…”);
        String s=y.readLine();
        Anagram ana = new Anagram();
        ana.anag(s, “”);
     }
    public void anag(String s1, String s2)
     {
            if(s1.length() == 0)
            {
                System.out.print(s2+”,”);
            }
            for(int i = 0; i < s1.length(); i++)
            {
                anag(s1.substring(0, i) + s1.substring(i+1, s1.length()), s1.charAt(i) + s2);
            }
     }
}
Advertisements
Comments
  1. Great program.Quite short and logical.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s