Anagrams:
Some times anagrams suits in a situation in which recursion provides a neat solution to a problem.A permutation is an arrangement of things in a definite order.Suppose you want to list all the anagrams of a specified words.
For example: Anagram of Cat:
Some times anagrams suits in a situation in which recursion provides a neat solution to a problem.A permutation is an arrangement of things in a definite order.Suppose you want to list all the anagrams of a specified words.
For example: Anagram of Cat:
- cat
- cta
- atc
- act
- tca
- tac
So Algorithm to write a program to anagram a word:
- Anagram the rightmost n-1 letters .
- Rotate all n letters.
- Repeat these steps n times.
Example Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
*/
/**
* @author Abhinaw.Tripathi
*
*/
public class AnagramApp
{
static int size;
static int count;
static char[] arrChar =new char[100];
public static void main(String[] args) throws IOException
{
System.out.println("Enter a word: ");
String input =getString();
size=input.length();
count=0;
for(int j=0;j<size;j++)
{
arrChar[j] =input.charAt(j);
doAnagram(size);
}
}
private static void doAnagram(int newsize)
{
if(newsize == 1)
{
return;
}
for(int i=0;i<newsize;i++)
{
doAnagram(newsize-1);
if(newsize==2)
displayWord();
rotate(newsize);
}
}
private static void rotate(int size2)
{
int j;
int position =size- size2;
char temp=arrChar[position];
for(j=-position+1;j<size;j++)
arrChar[j-1]=arrChar[j];
arrChar[j-1]=temp;
}
private static void displayWord()
{
if(count < 99)
System.out.println(" ");
if(count < 9)
System.out.println(" ");
System.out.println(++count + " ");
for(int j=0;j<size;j++)
System.out.println(arrChar[j]);
System.out.println(" ");
System.out.flush();
if(count%6 == 0)
System.out.println(" ");
}
private static String getString() throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String s=br.readLine();
return s;
}
}
No comments:
Post a Comment