Anagrams
Anagram is a type of word or phrase generating by rearranging the letters of a given word or phrase to produce a new word or phrase. Need to use all the original letters exactly once to frame new word or phrase. Some of the famous Anagram words are given below, |
Mother in law | Woman Hitler |
Debit card | Bad credit |
Eleven plus two | Twelve plus one |
Payment received | Every cent paid me |
Astronomer | Moon starer |
Dormitory | Dirty room |
Punishment | Nine Thumps |
Desperation | A rope ends it |
Snooze alarms | Alas! No more Zs |
and lot more are there...
Lets implement anagrams in java for only words to generate.
public class Anagram {
private HashSet<String> words = new HashSet<String>();
public static void main(String[] args) throws Exception {
String myWord = "art";
Anagram obj = new Anagram();
obj.getAnagramWords("", myWord);
obj.printAnagramWords();
}
public void getAnagramWords(String prefix, String word) {
if (word.length() <= 1) {
words.add(prefix+word);
} else {
for (int i = 0; i < word.length(); i++) {
String middle = word.substring(i, i + 1);
String before = word.substring(0, i);
String after = word.substring(i + 1);
getAnagramWords(prefix + middle, before + after);
}
}
}
public void printAnagramWords(){
System.out.println("LIST OF ANAGRAM WORDS :::");
for (String string : words) {
System.out.println(string);
}
}
}
OUTPUT:
LIST OF ANAGRAM WORDS :::
rta
atr
tra
art
tar
rat