1

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
  • Do you just want to count them, or also output them? Because the former is easier. By the way, farm has 4! = 24, not 28.
    – CompuChip
    Dec 9, 2013 at 15:05

1 Answer 1

0

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));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.