In: Computer Science
stone Atone aLone Clone clonS cOons coNns conEs coneY Money |
Word ladders were invented by Lewis Carroll in 1878, the author of Alice in Wonderland. A ladder is a sequence of words that starts at the starting word, ends at the ending word, In a word ladder puzzle you have to change one word into another by altering a single letter at each step. Each word in the ladder must be a valid English word and must have the same length. For example, to turn stone into money, one possible ladder is given on the left. Many ladder puzzles have more than one possible solution. Your program must determine the shortest word ladder. Another path from stone to money is stone store shore chore choke choky cooky cooey coney money Instructions Your program will accept starting and ending words from the input file called "infile.txt". Then, you read the dictionary file called “dictionary.txt '' store all words in a LinkedList. Finally, you build a word ladder between starting and ending words There are several ways to solve this problem. One simple method involves using stacks and queues. The algorithm (that you must implement) works as it follows Get the starting word and search through the dictionary to find all words that are one letter different. Create stacks for each of these words, containing the starting word (pushed first) and the word that is one letter different. Enqueue each of these stacks into a queue. This will create a queue of stacks! Then dequeue the first item (which is a stack) from the queue, look at its top word and compare it with the ending word. If they equal, you are done - this stack contains the ladder. Otherwise, you find all the words one letter different from it. For each of these new words create a deep copy of the stack and push each word onto the stack. Then enqueue those stacks to the queue. And so on. You terminate the process when you reach the ending word or the queue is empty. You have to keep track of used words! Otherwise, an infinite loop occurs. Example The starting word is smart. Find all the words one letter different from smart, push them into different stacks and store stacks in the queue. This table represents a queue of stacks. ---------------------------------------------------- Now dequeue the front and find all words one letter different from the top word scart. This will spawn seven stacks:
--------------------------------------------------------------------- which we enqueue to the queue. The queue size now is 11. Again dequeue the front and find all words one letter different from the top word start. This will spawn four stacks: ---------------------------------------- Add them to the queue. The queue size now is 14. Repeat the procedure until either you find the ending word or such a word ladder does not exist. Make sure you do not run into an infinite loop! Queue You are to implement a Queue data structure based on Java’s Queue class using LinkedList. Stack You are to use Java's Stack class. Output Your program must output to the console one word ladder from the start word to the end word. Every word in the ladder must be a word that appears in the dictionary. This includes the given start and end words--if they are not in the dictionary, you should print "There is no word ladder between ..." Remember that there may be more than one ladder between the start word and the end word. Your program may output any one of these ladders. The first output word must be the start word and the last output word must be the end word. If there is no way to make a ladder from the start word to the end word, your program must output "There is no word ladder between ..." |
import java.util.*;
import java.io.*;
public class WordLadder {
private static LinkedList< String >
dict;
private static LinkedList< String >
visited;
private static String start, end;
public static void main(String[] args) throws
IOException{
// TODO Auto-generated method stub
File dictfile = new
File("dictionary.txt");
File infile = new
File("infile.txt");
dict = new
LinkedList<>();
// load the dictionary
try(
Scanner in = new
Scanner(dictfile);){
while(in.hasNext()) {
dict.add(in.next());
}
}
try(Scanner in = new
Scanner(infile);)
{
while(in.hasNext()) {
start = in.next();
end = in.next();
if(start.length()!=end.length() || !dict.contains(start) ||
!dict.contains(end) ){
System.out.println("There is no word ladder between "+start+ " and
"+end);
continue;
}
findLadder(start,end);
}
}
}
public static void findLadder(String start,String end)
{
Queue< Stack< String >>
queue = new LinkedList<>();
visited = new
LinkedList<>();
Stack< String > copiedStack =
new Stack<>();
// Left as exercise
}
public static boolean isAnEdge(String w1, String w2)
{
// Left as
exercise
}
Output:
[line, fine]
[dear, fear]
There is no word ladder between stone and money
[fake, lake, lase, last, cast, cost, coat]
[like, line, fine, fire, fore, core, cord, cold, hold, held, help]
There is no word ladder between blue and pink
[face, fake, lake, like]
[help, held, hold, cold, cord, core, fore, fire, fine, find, mind]
[lice, line, fine, fire, fore, core, cord, cold, hold, held, help]
There is no word ladder between door and lice
import java.util.*;
import java.io.*;
public class test {
private static LinkedList< String > dict;
private static LinkedList< String > visited;
private static String start, end;
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
File dictfile = new File("dictionary.txt");
File infile = new File("infile.txt");
dict = new LinkedList<>();
// load the dictionary
try(Scanner in = new Scanner(dictfile);){
while(in.hasNext()) {
dict.add(in.next());
}
}
try(Scanner in = new Scanner(infile);)
{
while(in.hasNext()) {
start = in.next();
end = in.next();
if(start.length()!=end.length() || !dict.contains(start) || !dict.contains(end) ){
System.out.println("There is no word ladder between "+start+ " and "+end);
continue;
}
findLadder(start,end);
}
}
}
public static void findLadder(String start,String end) {
Queue< Stack< String >> queue = new LinkedList<>();
visited = new LinkedList<>();
Stack< String > currentStack = new Stack<>();
Stack<String> copiedStack = new Stack<>();
currentStack.push(start);
queue.offer(currentStack);
visited.add(start);
while( queue.size() != 0){
currentStack = queue.poll();
String current = currentStack.peek();
if( current.equals(end) ){
printAnswer(currentStack);
return;
}
for( String dictString: dict){
if( visited.contains(dictString) ) continue;
if( isAnEdge(current, dictString) ){
//making the deep coppy of the stack
copiedStack = new Stack<>();
copiedStack.addAll(currentStack);
copiedStack.push(dictString);
visited.add(dictString);
queue.offer(copiedStack);
}
}
}
// if we don't find the word ladder
System.out.println("There is no word ladder between "+start+ " and "+end);
}
public static void printAnswer(Stack<String> ans){
// temporay list to store the content of the stack in the reverse order
LinkedList<String> tempList = new LinkedList<>();
while(ans.size()!=0){
tempList.addFirst(ans.pop());
}
System.out.print("[");
for(int i=0; i< tempList.size(); i++){
if( i == tempList.size() -1 ) {
System.out.print(tempList.get(i));
} else {
System.out.print(tempList.get(i)+",");
}
}
System.out.println(']');
}
public static boolean isAnEdge(String w1, String w2) {
//if length are not same then return false;
if( w1.length() != w2.length() ){
return false;
}
//couting the difference between the two string if the difference count exceeds one then the strings are not in the ladder
int diffrenceCount = 0;
for(int i=0; i< w1.length() ;i++){
if( w1.charAt(i) != w2.charAt(i) ){
diffrenceCount++;
if(diffrenceCount >1){
return false;
}
}
}
if(diffrenceCount >1){
return false;
}
return true;
}
}