Sunday, May 4, 2014

Program to find out all possible combinations of a given word with all its alphabets - Anagram Solver

This question is often asked in many companies including amazon,goldmann sachs, Microsoft and google. I also encountered this question in my 2nd round with GoldMann Sachhs, Morgan Stanley. Although they take 6 rounds in all and unfortunately due to some HR discussion i came out, so just wanna share some thoughts on this problem.




The question is if i have given a word like 'tes' then print all the possible combinations of that word i.e if tes then possible combination are:-
'ets'
'ste'
'set'
'tes'-> given
'tse'
'est'

And then we have to maintain one dictionary and find out the word which is also present in that dictionary to make a meaningful word. 
To approach to this problem , lets bifurcate into two parts
1) First we will find all the possible combinations from the given word.
2) Read through the dictionary and then find out all the meaning ful words.
The program for the above is:-

package com.javaLearningHub;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class WordUtils {
public static Set<String> allAnagrams(String word) {
return allAnagrams("", word);
}

private static Set<String> allAnagrams(String prefix, String word) {
if (word.length() == 0) {
return Collections.singleton(prefix);
}
Set<String> aSet = new HashSet<String>();
for (int i = 0; i < word.length(); i++) {
aSet.addAll(allAnagrams(prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, word.length())));

}
return aSet;
}
}

 The main class for the above is:--


package com.javaLearningHub;


import java.util.Scanner;
import java.util.Set;

public class WordUtilsTest {

public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String for which you find all the combinations: ");
String word=sc.next();
Set<String> anagrams = WordUtils.allAnagrams(word);
System.out.println(anagrams);
}
}

The output for the above is:--

Enter the String for which you find all the combinations:
ank
[akn, nka, nak, kan, ank, kna]


To search it from a dictionary, i leave the logic to u.

In case of any queries, please feel free to post comments.



No comments:

Post a Comment