Question is from here:
Think of two familiar, unhyphenated, eight-letter words that contain the letters A, B, C, D, E and F, plus two others, in any order. What words are these?
Your task is to write a program to find the two words.
My Solution:
Firstly, we need a text file that contains all english words, I managed to find one here. Then all these words are read and stored in a HashSet. Next, I generate all permeation of a given string and check if dictionary contains any of them. When two words are found the program is terminated.
import java.io.*;
import java.util.*;
public class NPR_Sunday_Puzzle {
//given string
static String set = "abcdef";
//for adding two extra letters
static String [] al = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z"};
static Set<String> ans = new HashSet<String>();
static HashSet<String> dic = new HashSet<String>();
public static void main(String[] args) {
long begin = System.currentTimeMillis();
BufferedReader br = null;
try {
String s;
//locate this file on your PC
br = new BufferedReader(new FileReader("/enable1.txt"));
while ((s = br.readLine()) != null) {
//add English words to HashSet
dic.add(s);
}
} catch (IOException e) {
e.printStackTrace();
}
generate();
System.out.println("ANS: " + ans);
long end = System.currentTimeMillis();
System.out.println("Total execution time: " + (end-begin)/1000 + "s");
}
private static void generate(){
String s = "";
outter:
for (int i = 0; i < al.length; i++) {
for (int j = i + 1; j < al.length; j++) {
//adding extra two letters
s += al[i] + al[j];
permute("", set + s);
if(ans.size() == 2)
break outter;
s = "";
}
}
}
//generating all permutation of a given string
public static void permute(String beginningString, String endingString) {
if (endingString.length() <= 1){
//check if dic contains the word
if(dic.contains(beginningString + endingString)){
ans.add(beginningString + endingString);
return;
}
}
else
for (int i = 0; i < endingString.length(); i++) {
try {
String newString = endingString.substring(0, i) + endingString.substring(i + 1);
permute(beginningString + endingString.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
Output:
ANS: [feedback, boldface] Total execution time: 5s