Saturday 26 October 2013

Anagrams

/*We would like to generate all possible anagrams of a word. For example if the given word is 'TOP', there will be 6 possible anagrams:
       TOP
       TPO
       OPT
       OTP
       PTO
       POT

An anagram must be printed only once. You may output the anagrams in any order. Also output the total number of anagrams. You assume that the number of letter, n, in the word will be 7 at most, i.e. n<= 7
Test your program for the given data and some random data.

SAMPLE DATA:
     INPUT:
                       TO

OUTPUT:
                     TO
                     OT
Total number of anagrams = 2

INPUT :
                     LEAN
OUTPUT:
                     LEAN
                     LENA
                     LAEN
                     LANE
                     LNEA
                     LNAE
                     EALN
                     EANL
                     ELAN
                     ELNA
                     ENLA
                     ENAL
                     ALNE
                     ALEN
                     ANLE
                     ANEL
                     AENL
                     NLEA
                     NLAE
                     NELA
                     NEAL
                     NALE
                     NAEL
Total number of anagrams = 24
*/
import java.io.*;
public class Anagrams
{
    String str;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    int counter=0;
    public void take()throws Exception
    {
        System.out.println("\nEnter the word:");
        str=br.readLine();
        show("", str);
        System.out.println("Total number of anagrams ="+counter);
    }

    public void show(String s, String str)
    {
        if(str.length()<= 1)
        {
            counter++;
            System.out.println(s+str);
        }
        else
        {
            for(int i = 0; i< str.length(); i++)
            {
                String str1 = str.substring(i, i + 1);
                String str2 = str.substring(0, i);
                String str3 = str.substring(i + 1);
                show(s + str1, str2 + str3);
            }
        }
    }

    public static void main(String args[])throws Exception
    {
        Anagrams ob=new Anagrams();
        ob.take();
    }
}

No comments:

Post a Comment