Question

Design an algorithm which transforms a source word to a target word. for example: from head...

Design an algorithm which transforms a source word to a target word. for example: from head to tail. In each step, you just can replace one character, and the resulting word must be valid. You'll be given a dictionary. Your function must not only return if there is a path but spell the specific path: bool isThereValidPath(map validWords, string startWord, string endWord) {}

Program should be in java

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Solution :

Logic:

BFS can solve this problem .start with source word and check all words(to given dictionary) that adjacent (differ by one character) to current word and keep repeating this , until we find the word as target word.

// sample Input:

String[] words = {"poon","plee","same","poie","plie","poin","plea"}; // given dictionary word

        String source = "toon"; // source word
       String target = "plea"; // target word

//output :

true
Path follows..
[toon, poon, poin, poie, plie, plee, plea]

// If you have any doubt ,feel free to ask, Thank you .

import java.util.*;
import java.util.Map.Entry;

public class SourceToTarget {
  
   static ArrayList path = new ArrayList();

   static //To check if strings differ by exactly one character
   boolean checkDifference(String first, String second)
   {
       int count = 0; // to store count of differences
       int n = first.length();
      
       char[] firstArray = first.toCharArray();
       char[] secondArray = second.toCharArray();
      

       // Iterate through all characters and return false
       // if there are more than one mismatching characters
       for (int i = 0; i < n; i++)
       {
           if (firstArray[i] != secondArray[i]) {
               count++;
           }
           if (count > 1) {
               return false;
           }
       }
       return count == 1 ? true : false;
   }

   static boolean isThereValidPath(HashMap validWords, String source, String target) {
      
       // Create a queue for BFS and insert 'start' as source vertex
       Queue<String> queue = new LinkedList();
       queue.add(source);
       path.add(source);
       while(!queue.isEmpty()) {
          
           String current = queue.remove();
           Set<Entry<String,Integer>> entrySet = validWords.entrySet();
           Iterator<Entry<String,Integer>> itr = entrySet.iterator();
          
                while(itr.hasNext()) {
                  
                    Entry<String,Integer> entry = (Entry<String, Integer>) itr.next();
                    String key = entry.getKey();
                   if (checkDifference(current, key))
                   {
                       // Add the dictionary word to Q
                      
                      
                       String temp = key;
                       if(validWords.get(temp).equals(1)) {
                           path.add(key);
                           queue.add(key);
                           // Remove from dictionary so that this word is not
                           // processed again. This is like marking visited
                          
                           validWords.put(temp,0); // marking as visited
                           // If we reached target
                           if (temp.equals(target)) {
                              
                               return true;
                           }
                       }
                   }
                }

       }

       return false;  
   }

   public static void main(String[] args) {
       // TODO Auto-generated method stub
      
       // given words
       String[] words = {"poon","plee","same","poie","plie","poin","plea"};
      
       HashMap<String,Integer> validWords = new HashMap<String,Integer>();
       for(String w : words) {
           validWords.put(w,1);
       }

       String source = "toon";
       String target = "plea";
       System.out.println(isThereValidPath( validWords, source, target));
      
       System.out.println("Path follows..");
       System.out.println(path);

   }

}

Add a comment
Know the answer?
Add Answer to:
Design an algorithm which transforms a source word to a target word. for example: from head...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In this lab you will write a spell check program. The program has two input files:...

    In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the document to be spellchecked. The program will read in the words for the dictionary, then will read the document and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is or type in a replacement word and add...

  • Goal: design and implement a dictionary. implement your dictionary using AVL tree . Problem​: Each entry...

    Goal: design and implement a dictionary. implement your dictionary using AVL tree . Problem​: Each entry in the dictionary is a pair: (word, meaning). Word is a one-word string, meaning can be a string of one or more words (it’s your choice of implementation, you can restrict the meaning to one-word strings). The dictionary is case-insensitive. It means “Book”, “BOOK”, “book” are all the same . Your dictionary application must provide its operations through the following menu (make sure that...

  • For this lab you will write a Java program that plays a simple Guess The Word...

    For this lab you will write a Java program that plays a simple Guess The Word game. The program will prompt the user to enter the name of a file containing a list of words. These words mustbe stored in an ArrayList, and the program will not know how many words are in the file before it starts putting them in the list. When all of the words have been read from the file, the program randomly chooses one word...

  • Overview: The goal of this assignment is to implement a simple spell checker using a hash...

    Overview: The goal of this assignment is to implement a simple spell checker using a hash table. You will be given the basic guidelines for your implementation, but other than that you are free to determine and implement the exact classes and methods that you might need. Your spell-checker will be reading from two input files. The first file is a dictionary containing one word per line. The program should read the dictionary and insert the words into a hash...

  • Please follow all the instructions and do all the parts (a-d)! Create a Java program which implem...

    Please follow all the instructions and do all the parts (a-d)! Create a Java program which implements Dijkstra’s shortest path algorithm according to the psueudocode below. Base the design on the weighted graph implementation used in Problem3.java (provided at the bottom). Your program should include the following features: a. A new method receives a starting vertex index and a target vertex index (e.g. 0 and 4). It computes the shortest distances to all vertexes using Dijkstra’s algorithm. The pseudocode is...

  • Write a c++ program in that file to perform a “Search and Replace All” operation. This...

    Write a c++ program in that file to perform a “Search and Replace All” operation. This operation consists of performing a case-sensitive search for all occurrences of an arbitrary sequence of characters within a file and substituting another arbitrary sequence in place of them. Please note: One of the biggest problems some students have with this exercise occurs simply because they don’t read the command line information in the course document titled “Using the Compiler’s IDE”. Your program: 1. must...

  • Suppose that we want to help physicians to diagnose illnesses. A physician observes a patient's symptoms and considers the illnesses that could be associated with those symptoms. Design and implem...

    Suppose that we want to help physicians to diagnose illnesses. A physician observes a patient's symptoms and considers the illnesses that could be associated with those symptoms. Design and implement a class PhysiciansHelper thatprovide a list of those illnesses. PhysiciansHelper should contain a dictionary of illnesses and symptoms. A method should read a text file of illnesses and their symptoms into the dictionary. See format in sample data file. PhysiciansHelper should read a list of symptoms for a patient. A...

  • JAVA Primitive Editor (Please help, I am stuck on this assignment which is worth a lot...

    JAVA Primitive Editor (Please help, I am stuck on this assignment which is worth a lot of points. Make sure that the program works because I had someone answer this incorrectly!) The primary goal of the assignment is to develop a Java based primitive editor. We all know what an editor of a text file is. Notepad, Wordpad, TextWrangler, Pages, and Word are all text editors, where you can type text, correct the text in various places by moving the...

  • C Programming Take screenshot of compiled output once complete. (which should look similar to the sample...

    C Programming Take screenshot of compiled output once complete. (which should look similar to the sample one provided). Will rate positively. Problem: (1) Add PopTailSLL() as a new member function to the SLL abstract data type. “Unlink” the logically-last node (tail) from the list *sll, call the DestructElement function to destruct the object pointed-to by the node’s element data member, free() the node, and decrement size. A SLL_UNDERFLOW exception occurs when size = 0. void PopTailSLL(SLL *sll); Hint PopTailSLL() is...

  • You will be building a linked list. Make sure to keep track of both the head and tail nodes.

    Ch 8 Program: Playlist (Java)You will be building a linked list. Make sure to keep track of both the head and tail nodes.(1) Create two files to submit.SongEntry.java - Class declarationPlaylist.java - Contains main() methodBuild the SongEntry class per the following specifications. Note: Some methods can initially be method stubs (empty methods), to be completed in later steps.Private fieldsString uniqueID - Initialized to "none" in default constructorstring songName - Initialized to "none" in default constructorstring artistName - Initialized to "none"...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT