Java A jumble of a word w is obtained by rearranging the letters of the word in
ID: 3706434 • Letter: J
Question
Java
A jumble of a word w is obtained by rearranging the letters of the word in some random order. For example, if w = “tpra”, then “rapt”, “part”, “trap”, “ptra” are some of the jumbled words you can get out of w. Of these rapt, part, and trap are legit words in the dictionary whereas tpra and ptra are not.
Given a String w, the goal is to find if some jumble of w will give a legit word in the dictionary, and if so output at least one of those; otherwise, say that w does not have a legit jumbled word in the dictionary. Example: w =”ogd”, the answer is “god” or “dog”; if w = “pttt”, then w does not have a legit jumbled word in the dictionary.
You can use EnglishWordList.txt as the reference dictionary for valid/legit words. The given String can be of any length and you can assume it only has lowercase alphabetic characters. public void isValidJumble (String s)
EnglishWordList.txt
http://www-personal.umich.edu/~jlawler/wordlist
Explanation / Answer
Let me know if you have any doubts.
import java.io.File;
import java.util.Enumeration;
import java.util.Collections;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.HashSet;
import java.util.Set;
class Main {
public static Set<String> permutationFinder(String str) {
Set<String> perm = new HashSet<String>();
//Handling error scenarios
if (str == null) {
return null;
} else if (str.length() == 0) {
perm.add("");
return perm;
}
char initial = str.charAt(0); // first character
String rem = str.substring(1); // Full string without first character
Set<String> words = permutationFinder(rem);
for (String strNew : words) {
for (int i = 0;i<=strNew.length();i++){
perm.add(charInsert(strNew, initial, i));
}
}
return perm;
}
public static String charInsert(String str, char c, int j) {
String begin = str.substring(0, j);
String end = str.substring(j);
return begin + c + end;
}
public static void main(String[] args) throws FileNotFoundException {
Scanner sc1=new Scanner(System.in);
System.out.println("Enter the word");
String word1=sc1.next();
Set jumb = new HashSet();
jumb = permutationFinder(word1);
Enumeration e = Collections.enumeration(jumb);
while(e.hasMoreElements()) {
Scanner sc = new Scanner(new File("tiger.txt"));
String w2 = e.nextElement().toString();
while (sc.hasNext()) {
String word = sc.next();
if(w2.equals(word)) {
System.out.println("found--------------");
System.out.println(word);
System.exit(0);
}
}
sc.close();
}
System.out.println("Not present in dictionary");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.