Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Purpose: We have discussed recursion and in particular backtracking algorithms (such as Eight Queens). In this assignment you will get some practice at recursive programming

Purpose: We have discussed recursion and in particular backtracking algorithms (such as Eight Queens). In this assignment you will get some practice at recursive programming by writing a backtracking algorithm to find phrases in a puzzle.

Idea: "Word search" puzzles are common in newspapers, on restaurant placemats and even in their own collections within books. These vary in format from puzzle to puzzle, but one common format is as follows: A user is presented with a 2-dimensional grid of letters and a list of words. The user must find all of the words from the list within the grid, indicating where they are by drawing ovals around them. Words may be formed in any direction up, down, left or right (we will not allow diagonals even though most puzzles do allow them) but all of the letters in a word must be in a straight line.

This idea can be extended to allow phrases to be embedded in the grids. However, requiring an entire phrase to be in a straight line on the board is not practical, as the dimensions of the board would need to be overly large. Therefore, we will still require the letters in each word to be in a straight line, but we are allowed to change direction between words.

For example, we might be given the following 10x10 grid of letters:

a b s t r a c t i j

a t a d t d a t a j

t b c d c a g h t j

y b c d a t g h y j

p b c d t f l h e j

e b c d t f l h e j

s a r e s f o h s j

a r e d b f o h a j

r b c d a f c h r j

e r e a l l y r e j

and the following phrases:

abstract

abstract data types

abstract data types are really cool

abstract data types are really awesome

Upon searching, assuming the grid starts in the upper left corner with position (0,0), and that the row is the first coordinate:

abstract would be found in two places: [(0,0) to (0,7)] and [(8,4) to (1,4)]

abstract data types would also be found in two places: [(8,4) to (1,4)], [(1,5) to (1,8)], [(2,8) to (6,8)] and [(8,4) to (1,4)], [(1,3) to (1,0)], [(2,0) to (6,0)]

abstract data types are really cool would be found at: [(8,4) to (1,4)], [(1,3) to (1,0)], [(2,0) to (6,0)], [(7,0) to (9,0)], [(9,1) to (9,6)], [(8,6) to (5,6)]

abstract data types are really awesome would not be found.

Details: Your task is to write a Java program to read in a grid of letters from a file, and then interactively allow a user to enter phrases until he or she wants to quit. For each phrase your program must output whether or not the phrase is found and, if found, specifically where it is located.

Input Details: The grid of letters for your program will be stored in a text file formatted as follows:

Line 1: Two integers, R and C, separated by a single blank space. These will represent the number of rows, R, and columns, C, in the grid.

Remaining lines: R lines containing C lower case characters each.

The user input will be phrases of words, with a single space between each word and no punctuation. Each phrase will be entered on a single line. The user may enter either upper- or lower-case letters, but the string should be converted to lower-case before searching the grid. The program will end when the user enters no data for the current phrase (i.e., hits without typing any characters beforehand).

Output Details:

If a phrase is not found in the grid the output should simply state that fact.

If a phrase is found in the grid, your program must find one occurrence of the phrase, and the output must indicate this fact in two ways:

1) Show the coordinates of each word in the phrase as a pair of (row, column) pairs.

2) Show the grid with the letters of the phrase indicated in upper case

For example, for the grid above and the phrase "abstract data types" your output would be:

abstract: (8,4) to (1,4) data: (1,5) to (1,8) types: (2,8) to (6,8)

Algorithm Details: Your search algorithm must be a recursive, backtracking algorithm. Note that you do not need recursion to match the letters within individual words (although you may do this recursively if you prefer). Recursion is necessary when moving from one word to the next since it is here where you may change direction. To make the program more consistent (and easier to grade), we will have the following requirements for the recursive process:

1) No letter / location on the grid may appear more than one time in any part of a solution.

2) When given a choice of directions, the options must be tried in the following order: right, down, left, up. Given this ordering and the grid above, the solution for "abstract data" would be [(8,4) to (1,4)], [(1,5) to (1,8)] rather than [(8,4) to (1,4)], [(1,3) to (1,0)], since the "right" direction is tried before the "left" direction.

3) If the last letter in a word is at location (i, j), the first letter of the next word must be at one of locations (i, j+1), (i+1, j), (i, j-1), or (i-1, j).

4) The direction chosen to find the first letter of a word is the same direction that must be used for all of the letters of the word. For example, in the grid shown above, for the phrase "abstract data", the following would NOT be a valid solution: [(8,4) to (1,4)], [(1,5) to (4,5)]. This solution is not legal because we proceeded right from the "T" of "abstract" to find the "D" in "data", but then proceeded down to find the remaining letters in "data". Similarly, also in the grid shown above, for the phrase "abstract data types are", the following would NOT be a valid solution: [(8,4) to (1,4)], [(1,3) to (1,0)], [(2,0) to (6,0)], [(7,0) to (7,2)]. This solution is not legal because we proceeded down from the "S" of "types" to find the "A" in "are", but then proceeded right to find the remaining letters in "are".

The idea is that you are building a solution word by word. Each time you complete a word, you can look for the "next" word in any of the four directions this is where the recursion occurs. If the "next" word cannot be found in any of the directions, you must delete the most recently completed word and backtrack to the previous word.

For example, consider the board above with the search phrase "data types are really". The algorithm first tries to find the word "data" starting at position (0,0). It tries in all four directions and does not succeed. It proceeds through the other starting positions until it finds "data" in locations [(1,3) to (1,0)].

It now recursively tries to find "types" in the following ways:

Going right to position (1,1) this will not work since (1,1) is already being used in "data"

Going down to position (2, 0) this will succeed and "types" is found in locations [(2,0) to (6,0)].

The algorithm now recurses again, this time looking for "are" in the following ways:

Going right to position (6,1) this will succeed and "are" is found in locations [(6,1) to (6,3)].

The algorithm now recurses again, this time looking for "really" in the following ways:

Going right to position (6,4) this will not work since character (6,4) is an "s"

Going down to position (7,3) this will not work since character (7,3) is a "d"

Going left to position (6,2) this will not work since (6,2) is already being used in "are"

Going up to position (5,3) this will not work since character (5,3) is a "d"

Since all directions have been tried, the search for "really" has failed and the algorithm must backtrack.

The word "are" is removed and the previous search for "are" resumes

Going down to position (7,0) this will succeed and "are" is found in locations [(7,0) to (9,0)].

The algorithm now recurses again, this time looking for "really" in the following ways:

Going right to position (9,1) this will succeed and "really" is found in locations [(9,1) to (9,6)].

The last word in the phrase has been found and the algorithm succeeds

Clearly, more backtracking may be necessary in other situations. I recommend tracing through the process with some example phrases before you start coding your solution.

A non-trivial part of this assignment is keeping track of the "path" of the solution and printing the path out once the solution has been found. You will likely need to use some data structure to store / update this path. Think carefully how you can do this part of the assignment.

Provided Code

Find Word

// Backtracking example: Find a word within a two-d grid of characters

// Idea: A word can be formed by sequential letters in any of the 4 directions (right, down, left, up). Each letter in the grid

// can only be used one time within a word.

// Note: This program can help you with Assignment 3 by demonstrating how recursion / backtracking can be used to solve a problem. It will also show you how to read in and process the "board". However, be sure to realize that what you have to do is different from what you see here, and it is also more challenging. See more details in the

// Assignment 3 specifications.

import java.io.*;

import java.util.*;

public class FindWord

{

public static void main(String [] args)

{

new FindWord();

}

// Constructor to set things up and make the initial search call.

public FindWord()

{

Scanner inScan = new Scanner(System.in);

Scanner fReader;

File fName;

String fString = "", word = "";

// Make sure the file name is valid

while (true)

{

try

{

System.out.println("Please enter grid filename:");

fString = inScan.nextLine();

fName = new File(fString);

fReader = new Scanner(fName);

break;

}

catch (IOException e)

{

System.out.println("Problem " + e);

}

}

// Parse input file to create 2-d grid of characters

String [] dims = (fReader.nextLine()).split(" ");

int rows = Integer.parseInt(dims[0]);

int cols = Integer.parseInt(dims[1]);

char [][] theBoard = new char[rows][cols];

for (int i = 0; i < rows; i++)

{

String rowString = fReader.nextLine();

for (int j = 0; j < rowString.length(); j++)

{

theBoard[i][j] = Character.toLowerCase(rowString.charAt(j));

}

}

// Show user the grid

for (int i = 0; i < rows; i++)

{

for (int j = 0; j < cols; j++)

{

System.out.print(theBoard[i][j] + " ");

}

System.out.println();

}

System.out.println("Please enter the word to search for:");

word = (inScan.nextLine()).toLowerCase();

while (!(word.equals("")))

{

int x = 0, y = 0;

// Search for the word. Note the nested for loops here. This allows us to

// start the search at any of the locations in the board. The search itself

// is recursive (see findWord method for details). Note also the boolean

// which allows us to exit the loop before all of the positions have been

// tried -- as soon as one solution has been found we can stop looking.

boolean found = false;

for (int r = 0; (r < rows && !found); r++)

{

for (int c = 0; (c < cols && !found); c++)

{

// Start search for each position at index 0 of the word

found = findWord(r, c, word, 0, theBoard);

if (found)

{

x = r; // store starting indices of solution

y = c;

}

}

}

if (found)

{

System.out.println("The word: " + word);

System.out.println("was found starting at location (" + x + "," + y + ")");

for (int i = 0; i < rows; i++)

{

for (int j = 0; j < cols; j++)

{

System.out.print(theBoard[i][j] + " ");

theBoard[i][j] = Character.toLowerCase(theBoard[i][j]);

}

System.out.println();

}

}

else

{

System.out.println("The word: " + word);

System.out.println("was not found");

}

System.out.println("Please enter the word to search for:");

word = (inScan.nextLine()).toLowerCase();

}

}

// Recursive method to search for the word. Return true if found and false otherwise.

public boolean findWord(int r, int c, String word, int loc, char [][] bo)

{

//System.out.println("findWord: " + r + ":" + c + " " + word + ": " + loc); // trace code

// Check boundary conditions

if (r >= bo.length || r < 0 || c >= bo[0].length || c < 0)

return false;

else if (bo[r][c] != word.charAt(loc)) // char does not match

return false;

else // current character matches

{

bo[r][c] = Character.toUpperCase(bo[r][c]); // Change it to

// upper case. This serves two purposes:

// 1) It will no longer match a lower case char, so it will

// prevent the same letter from being used twice

// 2) It will show the word on the board when displayed boolean answer;

if (loc == word.length()-1) // base case - word found and we

answer = true; // are done!

else // Still have more letters to match, so recurse.

{ // Try all four directions if necessary (but only if necessary)

answer = findWord(r, c+1, word, loc+1, bo); // Right

if (!answer)

answer = findWord(r+1, c, word, loc+1, bo); // Down

if (!answer)

answer = findWord(r, c-1, word, loc+1, bo); // Left

if (!answer)

answer = findWord(r-1, c, word, loc+1, bo); // Up

// If answer was not found, backtrack. Note that in order to backtrack for this algorithm, we need to // move back in the board (r and c) and in the word index (loc) -- these are both handled via the //activation records, since after the current AR is popped, we revert to the previous values of these //variables.

// However, we also need to explicitly change the character back to lower case before backtracking.

if (!answer)

bo[r][c] = Character.toLowerCase(bo[r][c]);

}

return answer;

}

}

}

Test Codes:

9x8

a b c n u f n h f

u n f u n u h u b

f u e f f h n b u

n e u n h f b n f

u n u h u b c u e

f f h n f u n f u

n h a b n u f n g

h a b c d e f g h

output:

assig3 > java Assig3 Please enter grid filename: sample3.txt a b c n u f n h f u n f u n u h u b f u e f f h n b u n e u n h f b n f u n u h u b c u e f f h n f u n f u n h a b n u f n g h a b c d e f g h

Please enter phrase (sep. by single spaces): fun Looking for: fun containing 1 words The phrase: fun was found: fun: (0,5) to (0,3) a b c N U F n h f u n f u n u h u b f u e f f h n b u n e u n h f b n f u n u h u b c u e f f h n f u n f u n h a b n u f n g h a b c d e f g h

Please enter phrase (sep. by single spaces): fun fun Looking for: fun fun containing 2 words The phrase: fun fun was found: fun: (0,5) to (0,3) fun: (1,3) to (3,3) a b c N U F n h f u n F u n u h u b f U e f f h n b u N e u n h f b n f u n u h u b c u e f f h n f u n f u n h a b n u f n g h a b c d e f g h

Please enter phrase (sep. by single spaces): fun fun fun Looking for: fun fun fun containing 3 words The phrase: fun fun fun was found: fun: (0,5) to (0,3) fun: (1,3) to (3,3) fun: (4,3) to (6,3) a b c N U F n h f u n F u n u h u b f U e f f h n b u N e u n h f b n F u n u h u b c U e f f h n f u N f u n h a b n u f n g h a b c d e f g h

Please enter phrase (sep. by single spaces): fun fun fun fun Looking for: fun fun fun fun containing 4 words The phrase: fun fun fun fun was found: fun: (0,5) to (0,3) fun: (1,3) to (3,3) fun: (4,3) to (6,3) fun: (6,4) to (6,6) a b c N U F n h f u n F u n u h u b f U e f f h n b u N e u n h f b n F u n u h u b c U e f f h n f u N F U N h a b n u f n g h a b c d e f g h

Please enter phrase (sep. by single spaces): fun fun fun fun fun Looking for: fun fun fun fun fun containing 5 words The phrase: fun fun fun fun fun was found: fun: (0,5) to (0,3) fun: (1,3) to (3,3) fun: (4,3) to (6,3) fun: (6,4) to (6,6) fun: (5,6) to (3,6) a b c N U F n h f u n F u n u h u b f U e f f h n b u N e u N h f b n F u n U h u b c U e f F h n f u N F U N h a b n u f n g h a b c d e f g h

Please enter phrase (sep. by single spaces): fun fun fun fun fun fun Looking for: fun fun fun fun fun fun containing 6 words The phrase: fun fun fun fun fun fun was found: fun: (0,5) to (0,3) fun: (1,3) to (3,3) fun: (4,3) to (6,3) fun: (6,4) to (6,6) fun: (5,6) to (3,6) fun: (2,6) to (0,6) a b c N U F N h f u n F u n U h u b f U e f F h n b u N e u N h f b n F u n U h u b c U e f F h n f u N F U N h a b n u f n g h a b c d e f g h

Please enter phrase (sep. by single spaces): fun fun fun fun fun fun fun Looking for: fun fun fun fun fun fun fun containing 7 words The phrase: fun fun fun fun fun fun fun was found: fun: (1,0) to (3,0) fun: (4,0) to (6,0) fun: (6,1) to (6,3) fun: (6,4) to (6,6) fun: (5,6) to (3,6) fun: (2,6) to (0,6) fun: (0,5) to (0,3) a b c N U F N h F u n f u n U h U b f u e f F h N b u n e u N h F b n f u n U h U b c u e f F h N F U N F U N h a b n u f n g h a b c d e f g h

Please enter phrase (sep. by single spaces): fun fun fun fun fun fun fun fun Looking for: fun fun fun fun fun fun fun fun containing 8 words The phrase: fun fun fun fun fun fun fun fun was found: fun: (1,0) to (3,0) fun: (4,0) to (6,0) fun: (6,1) to (6,3) fun: (6,4) to (6,6) fun: (5,6) to (3,6) fun: (2,6) to (0,6) fun: (0,5) to (0,3) fun: (1,3) to (3,3) a b c N U F N h F u n F u n U h U b f U e f F h N b u N e u N h F b n f u n U h U b c u e f F h N F U N F U N h a b n u f n g h a b c d e f g h

Please enter phrase (sep. by single spaces): fun fun fun fun fun fun fun fun fun Looking for: fun fun fun fun fun fun fun fun fun containing 9 words The phrase: fun fun fun fun fun fun fun fun fun was not found

Please enter phrase (sep. by single spaces):

It should capitalize where it finds the words when put through the output.

If you have any questions or I need to clear anything up for you just ask. The text editor here isnt the best for these long posts.

Thank you!!!

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Management System MCQs Multiple Choice Questions And Answers

Authors: Arshad Iqbal

1st Edition

1073328554, 978-1073328550

More Books

Students also viewed these Databases questions

Question

1. What is the tone of the comments? How can they be improved?

Answered: 1 week ago

Question

5. Identify the logical fallacies, deceptive forms of reasoning

Answered: 1 week ago

Question

6. Choose an appropriate organizational strategy for your speech

Answered: 1 week ago