how to count all possible Anagrams in java programming

2.7k views Asked by At

i want to count all possible anagram of input words i want to add counter that count all anagrams

for ex. the string farm have 28 possible anagram i want this output

Enter String: abc

here are all the anagrams of : abc

abc acb bac bca cba cab

the String "abc" have 6 possible anagram

"this is the code "

  import java.util.Scanner; 
  public class Anagrams1 { 

  public static void main (String args[]) { 

  Scanner r = new Scanner(System.in);  

  System.out.print("Enter a string:"); 
  String s = r.next(); 


  char[] text = new char[s.length()]; 
  for (int i=0; i<s.length(); i++) 
  text[i] = s.charAt(i); 

  System.out.println("Here are all the anagrams of " + s); 
  makeAnagram(text,0); 
  System.out.println("Goodbye!"); 


  } 
   static void makeAnagram(char[] a, int i) { 


    if (i == a.length-1) { 

    printArray(a); 

  } 
  else { 
  for (int j=i; j< a.length; j++) { 

  char c = a[i]; 
  a[i] = a[j]; 
  a[j] = c; 

  makeAnagram(a, i+1); 


  c = a[i]; 
  a[i] = a[j]; 
  a[j] = c; 


   } 
 } 
 }  


  static void printArray(char [] a) 
 { 

 for (int i=0; i< a.length; i++) 
 System.out.print(a[i]); 
   System.out.println(); 

  } 

}
1

There are 1 answers

0
hyper-neutrino On

If you are counting the number of anagrams of input str, the number is factorial(str.length()) where

public static final int factorial(int base) {
    return (base == 1) ? (1) : (factorial(base - 1));
}