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,OTP,OPT,PTO,POT
An anagram must be printed only once you may output
the anagram in any order. Also output the total number of anagrams. You may
assume that the numbers of letters, 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,
ELAN, ELNA, EALN, EANL, ENLA, ENAL, ALEN,
ALNE, AELN, AENL, ANLE, ANEL, NLEA, NLAE, NELA, NEAL, NALE, NAEL
Total
number of anagrams= 24
Solution:-
import java.util.*;
class anagrams
{
static String in;
int count=1;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter A
Word");
in=sc.next();
}
void total()
{
for(int i=1;i<=in.length();i++)
{
count=count*i;
}
System.out.println("Total Number
of Anagrams are "+count);
}
void permutation(String prefix,String str)//Function Will Find Anagrams Through Recursion...
{
int n=str.length();
if(n==0)System.out.print(prefix+"\t");
else
{
for(int i=0;i<n;i++)
{
permutation(prefix+str.charAt(i),str.substring(0,i)+str.substring(i+1,n));
}
}
}
public static void main(String args[])
{
anagrams obj=new anagrams();
obj.input();
obj.total();
obj.permutation("",in);
}
}
No comments:
Post a Comment