Sunday , 15 October 2017
Home » ISC Important Programs » Java program to find all the Anagrams of a word

Java program to find all the Anagrams of a word

Question:

Write a Program in Java to input a word and print its anagrams..

Note: Anagrams are words made up of all the characters present in the original word by re-arranging the characters.

Example: Anagrams of the word TOP are: TOP, TPO, OPT, OTP, PTO and POT

Programming Code:

/**
* The class Anagrams inputs a word and generates its anagrams
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.util.*;
class Anagrams
{
    int c = 0;
    
    void input()throws Exception
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word : ");
        String s = sc.next();
        System.out.println("The Anagrams are : ");
        display("",s);
        System.out.println("Total Number of Anagrams = "+c);
    }
  
    void display(String s1, String s2)
    {
        if(s2.length()<=1)
        {
            c++;
            System.out.println(s1+s2);
        }
        else
        {
            for(int i=0; i<s2.length(); i++)
            {
                String x = s2.substring(i, i+1);
                String y = s2.substring(0, i);
                String z = s2.substring(i+1);
                display(s1+x, y+z);
            }
        }
    }
    
    public static void main(String args[])throws Exception
    {
        Anagrams ob=new Anagrams();
        ob.input();
    }
}

Output:

Enter a word : BACK
The Anagrams are : 
BACK
BAKC
BCAK
BCKA
BKAC
BKCA
ABCK
ABKC
ACBK
ACKB
AKBC
AKCB
CBAK
CBKA
CABK
CAKB
CKBA
CKAB
KBAC
KBCA
KABC
KACB
KCBA
KCAB
Total Number of Anagrams = 24

Check Also

[Question 2] ISC 2017 Computer Practical Paper Solved – Quiz Result

Solution of Program 2 of ISC 2017 Computer Science Paper 2 (Practical) Exam. Java program to input the answers of each participant row-wise and calculate their marks

2 comments

  1. Hi,
    I have a small doubt. If we input ‘TOO’ then it gives the output
    Enter a word : TOO
    The Anagrams are :
    TOO
    TOO
    OTO
    OOT
    OTO
    OOT
    Total Number of Anagrams = 6
    Is this output correct?

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *