SlideShare a Scribd company logo
1 of 11
Download to read offline
hello the code given is mostly complete but I need help with the Solver portion please
Consider a maze made up of rectangular array of squares, such as the following one:
X X X X X X X X X X X X X
X X X X X X
X X X X X
X X X X X X X X
X X X X X
X X X X X X X
X X X X X X X X X X X X X
Figure 1--- A sample maze
The X blocks represent a blocked square and form the walls of the maze. Let us consider mazes
that
have only one entrance and one exit, as in our example. Beginning at the entrance at the top left
side of
the maze, find a path to the exit at the bottom right side. You can move only up, down, left, or
right.
Square is either clear or blocked by an X character.
Let a two-dimensional array represent the maze. Use a stack data structure to find a path through
the
maze. Some mazes might have more than one successful path, while others might have no path.
Hints:
The primary consideration is that if you reach a dead end, you need to be able to backtrack
along the path to the point where you can try a different path. The stack data structure makes it
possible to store the current path and backtrack if necessary. Every clear position visited in the
current path is pushed to the stack and if a dead end is reached, the previous position is popped
from the stack to backtrack. You need to have a loop that begins with the start position and
pushes it into the stack then moves to a neighboring cell until either the goal position is reached,
or the stack becomes empty.
Make sure to mark each clear array cell you move to as visited to avoid checking it again and
getting stuck in an infinite loop. For example, each array cell can have three different values: X
for blocked, V for visited, and for clear.
A dead end is an array cell whose all neighbors are either blocked or already visited.
There are four files you should pay attention to:
Position.java: a class to store the position of an array cell. It has two attributes: row and
column along with their accessor and mutator methods. It also has an equals method that
checks for equality of two Position objects.
Maze.java: a class to store a maze. It has 3 attributes: a two-dimensional character array which
represents the maze, a Position object to represent the start location, and another Position
object to represent the stop location.
MazeSolver: This class contains one static method, solve. It accepts a maze and returns an
array of Positions that is used to traverse the maze if the maze is solvable. If the maze is not
solvable then an empty array is returned.
o Keep in mind that stacks store objects in reverse order so be sure to return the position
array in the correct order.
Tester: a sample driver class which calls the traverse method on a maze in either the
SolvableMaze, UnsolvableMaze, or HugeSolvableMaze files. These should be at the root of the
project folder
SOLVER
import java.util.Stack;
public class MazeSolver {
public static Position[] solve(Maze maze) {
return null;
}
}
POSITION
public class Position {
private int row;
private int column;
public Position(int row, int column) {
this.row = row;
this.column = column;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Position)) {
return false;
}
Position otherPosition = (Position) obj;
return (otherPosition.row == row && otherPosition.column == column);
}
public String toString() {
return "row:" + row + " column:" + column;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}
MAZE
public class Maze {ate final char[][] maze;
private final Position start, end;
public Maze(char[][] maze, Position start, Position end) {
this.maze = maze;
if (validPosition(start)) {
this.start = start;
} else {
throw new PositionNotValidException("The start position is valid for the maze: " +
start);
}
if (validPosition(end)) {
this.end = end;
} else {
throw new PositionNotValidException("The stop position is valid for the maze: " + end);
}
}
public Position getStart() {
return start;
}
public Position getEnd() {
return end;
}
public int numRows() {
return maze.length;
}
public int numCols(int row) {
return maze[row].length;
}
public boolean validPosition(int row, int col) {
if (row >= 0 && row < maze.length) {
if (col >= 0 && col < maze[row].length) {
return true;
}
}
return false;
}
public boolean validPosition(Position pos) {
return validPosition(pos.getRow(), pos.getColumn());
}
public char getAt(Position pos) {
if (validPosition(pos)) {
return maze[pos.getRow()][pos.getColumn()];
} else {
String msg = String.format("The position given is not valid: %s", pos.toString());
throw new PositionNotValidException(msg);
}
}
public char getAt(int row, int column) {
if (validPosition(row, column)) {
return maze[row][column];
} else {
String msg = String.format("The row and column given is not valid: row %d col %d",
row, column);
throw new PositionNotValidException(msg);
}
}
public void setAt(Position pos, char c) {
if (validPosition(pos)) {
setAt(pos.getRow(), pos.getColumn(), c);
} else {
String msg = String.format("The position given is not valid: %s", pos.toString());
throw new PositionNotValidException(msg);
}
}
public void setAt(int row, int column, char c) {
if (validPosition(row, column)) {
maze[row][column] = c;
} else {
String msg = String.format("The row and column given is not valid: row %d col %d",
row, column);
throw new PositionNotValidException(msg);
}
}
public Maze clone() {
char clone[][] = new char[maze.length][];
for (int r = 0; r < maze.length; r++) {
clone[r] = new char[maze[r].length];
for (int c = 0; c < maze[r].length; c++) {
clone[r][c] = maze[r][c];
}
}
return new Maze(clone, start, end);
}
public String toString() {
StringBuffer sb = new StringBuffer();
for (int r = 0; r < maze.length; r++) {
sb.append(maze[r]);
sb.append("n");
}
return sb.toString();
}
}
POSITIONEXCEPTION
public class PositionNotValidException extends RuntimeException {
public PositionNotValidException() {
super();
}
public PositionNotValidException(String msg) {
super(msg);
}
private static final long serialVersionUID = 1L;
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
import maze.Maze;
import maze.MazeSolver;
import maze.Position;
/**
* Driver class to test students solution. The printed result should be a path
* from the start to the finish where the path is represented by asterisks.
*
* The Solvable and Unsolvable mazes were generated using
* https://www.dcode.fr/maze-generator
*
*
*/
public class Tester {
private static Maze loadMaze(String file) {
char maze[][] = null;
Position start = null, stop = null;
try {
Scanner filein = new Scanner(new File(file));
// Load Header
// First number is how many rows.
// Second and third number are the row and column to start at.
// Fourth and fifth number are the row and column to stop at.
int row = filein.nextInt();
start = new Position(filein.nextInt(), filein.nextInt());
stop = new Position(filein.nextInt(), filein.nextInt());
filein.nextLine();
// End Header
maze = new char[row][];
int currRow = 0;
while (filein.hasNextLine()) {
maze[currRow++] = filein.nextLine().replace("n", "").toCharArray();
}
filein.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
System.exit(1);
} catch (Exception e) {
System.out.println("Something bad happened. See exception message");
e.printStackTrace();
System.exit(2);
}
return new Maze(maze, start, stop);
}
private static void walkPath(Maze maze, Position traversal[]) {
Position previous = null;
for (Position p : traversal) {
if (maze.getAt(p) == ' ') {
maze.setAt(p, 'O');
} else if (maze.getAt(p) == 'O') {
System.out.println("MISTAKE");
System.out.println("There is a repeated position " + p);
System.exit(3);
} else {
System.out.println("MISTAKE");
System.out.println("There is an obstacle at position " + p);
System.out.println(maze);
System.exit(3);
}
// Check to make sure path is connected.
if (previous != null) {
int prevRow = previous.getRow();
int prevCol = previous.getColumn();
int curRow = p.getRow();
int curCol = p.getColumn();
boolean isPathConnected = false;
if (curRow - 1 == prevRow || curRow + 1 == prevRow) {
isPathConnected = curCol == prevCol;
} else if (curCol - 1 == prevCol || curCol + 1 == prevCol) {
isPathConnected = curRow == prevRow;
}
if (!isPathConnected) {
System.out.println("Path not connected");
System.out.println("From: " + previous);
System.out.println("To: " + p);
maze.setAt(previous, '?');
maze.setAt(p, '?');
System.out.println(maze);
System.exit(3);
}
}
previous = p;
}
}
private static void printDialog() {
System.out.println("Pick an option");
System.out.println("1: Solvable Maze");
System.out.println("2: Unsolvable Maze");
System.out.println("3: Huge Unsolvable Maze");
System.out.println("4: EXIT");
}
private static int getChoice(Scanner in) {
boolean exit = false;
int choice = 0;
do {
try {
System.out.print(">> ");
choice = Integer.parseInt(in.nextLine());
if (choice > 0 && choice <= 4) {
exit = true;
} else {
System.out.println("Choice must be either 1, 2, 3, or 4.");
}
} catch (InputMismatchException e) {
System.out.println("Choice must be either 1, 2, 3, or 4.");
}
} while (!exit);
return choice;
}
public static void main(String[] args) {
Maze clone;
Position solution[];
Scanner userIn = new Scanner(System.in);
boolean exit = false;
while (!exit) {
printDialog();
int choice = getChoice(userIn);
switch (choice) {
case 1:
/** Solvable Maze ***/
Maze solvableMaze = loadMaze("SolvableMaze");
clone = solvableMaze.clone();
System.out.println("Testing Solvable Maze");
System.out.println("Starts at " + clone.getStart());
System.out.println("Ends at " + clone.getEnd());
System.out.println(clone);
solution = MazeSolver.solve(clone);
if (solution.length != 0) {
walkPath(solvableMaze, solution);
System.out.println("nSOLUTION");
System.out.println(solvableMaze);
} else {
System.out.println("Null returned but maze is solvable.n");
}
break;
/*****************************************************************************
**/
case 2:
/** Unsolvable Maze **/
Maze unsolvableMaze = loadMaze("UnsolvableMaze");
clone = unsolvableMaze.clone();
System.out.println("Testing Unsolvable Maze");
System.out.println(clone);
solution = MazeSolver.solve(clone);
if (solution.length == 0) {
System.out.println("CORRECT");
System.out.println("This maze is unsolvable so an empty array should be
returned.");
} else {
System.out.println("INCORRECT");
System.out.println("This maze is unsolvable. An empty array should be returned.");
}
break;
/*****************************************************************************
***/
/** Huge Solvable Maze **/
case 3:
Maze hugeSolvableMaze = loadMaze("HugeSolvableMaze");
clone = hugeSolvableMaze.clone();
System.out.println("Testing Huge Solvable Maze");
System.out.println("Starts at " + clone.getStart());
System.out.println("Ends at " + clone.getEnd());
System.out.println(clone);
solution = MazeSolver.solve(clone);
if (solution.length != 0) {
walkPath(hugeSolvableMaze, solution);
System.out.println("nSOLUTION");
System.out.println(hugeSolvableMaze);
} else {
System.out.println("Null returned but maze is solvable.n");
}
break;
case 4:
exit = true;
}
}
System.out.println("Exitting!");
}
}

More Related Content

Similar to hello the code given is mostly complete but I need help with the Sol.pdf

Prolog 01
Prolog 01Prolog 01
Prolog 01saru40
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++Vikash Dhal
 
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfN Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfakashreddy966699
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type PatternsSimon Ritter
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
10 Recursion
10 Recursion10 Recursion
10 Recursionmaznabili
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Philip Schwarz
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfdbrienmhompsonkath75
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
About java
About javaAbout java
About javaJay Xu
 
need help with this java lab please read below and follow the steps.pdf
need help with this java lab please read below and follow the steps.pdfneed help with this java lab please read below and follow the steps.pdf
need help with this java lab please read below and follow the steps.pdfarjuntiwari586
 
I am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdfI am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdffortmdu
 
1 OverviewFor this lab, you will implement the insert method and t.pdf
1 OverviewFor this lab, you will implement the insert method and t.pdf1 OverviewFor this lab, you will implement the insert method and t.pdf
1 OverviewFor this lab, you will implement the insert method and t.pdfrajeshjain2109
 

Similar to hello the code given is mostly complete but I need help with the Sol.pdf (20)

Prolog 01
Prolog 01Prolog 01
Prolog 01
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
 
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfN Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Lec2
Lec2Lec2
Lec2
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdf
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
About java
About javaAbout java
About java
 
Knight's Tour
Knight's TourKnight's Tour
Knight's Tour
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
need help with this java lab please read below and follow the steps.pdf
need help with this java lab please read below and follow the steps.pdfneed help with this java lab please read below and follow the steps.pdf
need help with this java lab please read below and follow the steps.pdf
 
I am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdfI am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdf
 
1 OverviewFor this lab, you will implement the insert method and t.pdf
1 OverviewFor this lab, you will implement the insert method and t.pdf1 OverviewFor this lab, you will implement the insert method and t.pdf
1 OverviewFor this lab, you will implement the insert method and t.pdf
 
The string class
The string classThe string class
The string class
 

More from almonardfans

1.For the standard (reference) SpMV algorithm, does the communicatio.pdf
1.For the standard (reference) SpMV algorithm, does the communicatio.pdf1.For the standard (reference) SpMV algorithm, does the communicatio.pdf
1.For the standard (reference) SpMV algorithm, does the communicatio.pdfalmonardfans
 
1.Does ZeRO propose solution for memory- or compute-bounded problem.pdf
1.Does ZeRO propose solution for memory- or compute-bounded problem.pdf1.Does ZeRO propose solution for memory- or compute-bounded problem.pdf
1.Does ZeRO propose solution for memory- or compute-bounded problem.pdfalmonardfans
 
1.Early versions of Supply chain included physical distribution and .pdf
1.Early versions of Supply chain included physical distribution and .pdf1.Early versions of Supply chain included physical distribution and .pdf
1.Early versions of Supply chain included physical distribution and .pdfalmonardfans
 
1.A tee with 33 tips will be given, with three of them filled by�D.pdf
1.A tee with 33 tips will be given, with three of them filled by�D.pdf1.A tee with 33 tips will be given, with three of them filled by�D.pdf
1.A tee with 33 tips will be given, with three of them filled by�D.pdfalmonardfans
 
1.A person is said to have referent power over you to the extent tha.pdf
1.A person is said to have referent power over you to the extent tha.pdf1.A person is said to have referent power over you to the extent tha.pdf
1.A person is said to have referent power over you to the extent tha.pdfalmonardfans
 
1. �Son precisas y veraces las afirmaciones de marketing de Smiths .pdf
1. �Son precisas y veraces las afirmaciones de marketing de Smiths .pdf1. �Son precisas y veraces las afirmaciones de marketing de Smiths .pdf
1. �Son precisas y veraces las afirmaciones de marketing de Smiths .pdfalmonardfans
 
1. �Qu� ventajas y desventajas encontraron las primeras plantas que .pdf
1. �Qu� ventajas y desventajas encontraron las primeras plantas que .pdf1. �Qu� ventajas y desventajas encontraron las primeras plantas que .pdf
1. �Qu� ventajas y desventajas encontraron las primeras plantas que .pdfalmonardfans
 
1.2 Practice (SOA Sample Q127) A company owes 500 and 1,000 to be pa.pdf
1.2 Practice (SOA Sample Q127) A company owes 500 and 1,000 to be pa.pdf1.2 Practice (SOA Sample Q127) A company owes 500 and 1,000 to be pa.pdf
1.2 Practice (SOA Sample Q127) A company owes 500 and 1,000 to be pa.pdfalmonardfans
 
1. �Qu� evento convenci� a Netflix para cambiar a un servicio basado.pdf
1. �Qu� evento convenci� a Netflix para cambiar a un servicio basado.pdf1. �Qu� evento convenci� a Netflix para cambiar a un servicio basado.pdf
1. �Qu� evento convenci� a Netflix para cambiar a un servicio basado.pdfalmonardfans
 
1.. Todos los siguientes elementos han sido identificados como impor.pdf
1.. Todos los siguientes elementos han sido identificados como impor.pdf1.. Todos los siguientes elementos han sido identificados como impor.pdf
1.. Todos los siguientes elementos han sido identificados como impor.pdfalmonardfans
 
1.----A method which enables the user to specify conditions to displ.pdf
1.----A method which enables the user to specify conditions to displ.pdf1.----A method which enables the user to specify conditions to displ.pdf
1.----A method which enables the user to specify conditions to displ.pdfalmonardfans
 
1. �Cu�les son los seis pasos de un proceso de selecci�n de puestos .pdf
1. �Cu�les son los seis pasos de un proceso de selecci�n de puestos .pdf1. �Cu�les son los seis pasos de un proceso de selecci�n de puestos .pdf
1. �Cu�les son los seis pasos de un proceso de selecci�n de puestos .pdfalmonardfans
 
1.) Una mujer que tiene sangre tipo A positiva tiene una hija que es.pdf
1.) Una mujer que tiene sangre tipo A positiva tiene una hija que es.pdf1.) Una mujer que tiene sangre tipo A positiva tiene una hija que es.pdf
1.) Una mujer que tiene sangre tipo A positiva tiene una hija que es.pdfalmonardfans
 
1. �Cu�l es la diferencia entre una bacteria F + y una Hfr d. Las.pdf
1. �Cu�l es la diferencia entre una bacteria F + y una Hfr d. Las.pdf1. �Cu�l es la diferencia entre una bacteria F + y una Hfr d. Las.pdf
1. �Cu�l es la diferencia entre una bacteria F + y una Hfr d. Las.pdfalmonardfans
 
1. �Cu�les de las siguientes afirmaciones sobre los or�genes de la a.pdf
1. �Cu�les de las siguientes afirmaciones sobre los or�genes de la a.pdf1. �Cu�les de las siguientes afirmaciones sobre los or�genes de la a.pdf
1. �Cu�les de las siguientes afirmaciones sobre los or�genes de la a.pdfalmonardfans
 
1. �Cu�l es la relaci�n entre Enron y SOX La quiebra y el esc�n.pdf
1. �Cu�l es la relaci�n entre Enron y SOX La quiebra y el esc�n.pdf1. �Cu�l es la relaci�n entre Enron y SOX La quiebra y el esc�n.pdf
1. �Cu�l es la relaci�n entre Enron y SOX La quiebra y el esc�n.pdfalmonardfans
 
1.) Imagina tres puntos en un mapa topogr�fico que est�n ubicados en.pdf
1.) Imagina tres puntos en un mapa topogr�fico que est�n ubicados en.pdf1.) Imagina tres puntos en un mapa topogr�fico que est�n ubicados en.pdf
1.) Imagina tres puntos en un mapa topogr�fico que est�n ubicados en.pdfalmonardfans
 
1. �Qu� es la dominancia apical 2. �Cu�l es el papel de la auxina.pdf
1. �Qu� es la dominancia apical 2. �Cu�l es el papel de la auxina.pdf1. �Qu� es la dominancia apical 2. �Cu�l es el papel de la auxina.pdf
1. �Qu� es la dominancia apical 2. �Cu�l es el papel de la auxina.pdfalmonardfans
 
1. �Por qu� no hubo un plan de sucesi�n en Lakkard Leather Carl F.pdf
1. �Por qu� no hubo un plan de sucesi�n en Lakkard Leather Carl F.pdf1. �Por qu� no hubo un plan de sucesi�n en Lakkard Leather Carl F.pdf
1. �Por qu� no hubo un plan de sucesi�n en Lakkard Leather Carl F.pdfalmonardfans
 
1. �Por qu� la nube es importante para ciudades como Dubuque mientra.pdf
1. �Por qu� la nube es importante para ciudades como Dubuque mientra.pdf1. �Por qu� la nube es importante para ciudades como Dubuque mientra.pdf
1. �Por qu� la nube es importante para ciudades como Dubuque mientra.pdfalmonardfans
 

More from almonardfans (20)

1.For the standard (reference) SpMV algorithm, does the communicatio.pdf
1.For the standard (reference) SpMV algorithm, does the communicatio.pdf1.For the standard (reference) SpMV algorithm, does the communicatio.pdf
1.For the standard (reference) SpMV algorithm, does the communicatio.pdf
 
1.Does ZeRO propose solution for memory- or compute-bounded problem.pdf
1.Does ZeRO propose solution for memory- or compute-bounded problem.pdf1.Does ZeRO propose solution for memory- or compute-bounded problem.pdf
1.Does ZeRO propose solution for memory- or compute-bounded problem.pdf
 
1.Early versions of Supply chain included physical distribution and .pdf
1.Early versions of Supply chain included physical distribution and .pdf1.Early versions of Supply chain included physical distribution and .pdf
1.Early versions of Supply chain included physical distribution and .pdf
 
1.A tee with 33 tips will be given, with three of them filled by�D.pdf
1.A tee with 33 tips will be given, with three of them filled by�D.pdf1.A tee with 33 tips will be given, with three of them filled by�D.pdf
1.A tee with 33 tips will be given, with three of them filled by�D.pdf
 
1.A person is said to have referent power over you to the extent tha.pdf
1.A person is said to have referent power over you to the extent tha.pdf1.A person is said to have referent power over you to the extent tha.pdf
1.A person is said to have referent power over you to the extent tha.pdf
 
1. �Son precisas y veraces las afirmaciones de marketing de Smiths .pdf
1. �Son precisas y veraces las afirmaciones de marketing de Smiths .pdf1. �Son precisas y veraces las afirmaciones de marketing de Smiths .pdf
1. �Son precisas y veraces las afirmaciones de marketing de Smiths .pdf
 
1. �Qu� ventajas y desventajas encontraron las primeras plantas que .pdf
1. �Qu� ventajas y desventajas encontraron las primeras plantas que .pdf1. �Qu� ventajas y desventajas encontraron las primeras plantas que .pdf
1. �Qu� ventajas y desventajas encontraron las primeras plantas que .pdf
 
1.2 Practice (SOA Sample Q127) A company owes 500 and 1,000 to be pa.pdf
1.2 Practice (SOA Sample Q127) A company owes 500 and 1,000 to be pa.pdf1.2 Practice (SOA Sample Q127) A company owes 500 and 1,000 to be pa.pdf
1.2 Practice (SOA Sample Q127) A company owes 500 and 1,000 to be pa.pdf
 
1. �Qu� evento convenci� a Netflix para cambiar a un servicio basado.pdf
1. �Qu� evento convenci� a Netflix para cambiar a un servicio basado.pdf1. �Qu� evento convenci� a Netflix para cambiar a un servicio basado.pdf
1. �Qu� evento convenci� a Netflix para cambiar a un servicio basado.pdf
 
1.. Todos los siguientes elementos han sido identificados como impor.pdf
1.. Todos los siguientes elementos han sido identificados como impor.pdf1.. Todos los siguientes elementos han sido identificados como impor.pdf
1.. Todos los siguientes elementos han sido identificados como impor.pdf
 
1.----A method which enables the user to specify conditions to displ.pdf
1.----A method which enables the user to specify conditions to displ.pdf1.----A method which enables the user to specify conditions to displ.pdf
1.----A method which enables the user to specify conditions to displ.pdf
 
1. �Cu�les son los seis pasos de un proceso de selecci�n de puestos .pdf
1. �Cu�les son los seis pasos de un proceso de selecci�n de puestos .pdf1. �Cu�les son los seis pasos de un proceso de selecci�n de puestos .pdf
1. �Cu�les son los seis pasos de un proceso de selecci�n de puestos .pdf
 
1.) Una mujer que tiene sangre tipo A positiva tiene una hija que es.pdf
1.) Una mujer que tiene sangre tipo A positiva tiene una hija que es.pdf1.) Una mujer que tiene sangre tipo A positiva tiene una hija que es.pdf
1.) Una mujer que tiene sangre tipo A positiva tiene una hija que es.pdf
 
1. �Cu�l es la diferencia entre una bacteria F + y una Hfr d. Las.pdf
1. �Cu�l es la diferencia entre una bacteria F + y una Hfr d. Las.pdf1. �Cu�l es la diferencia entre una bacteria F + y una Hfr d. Las.pdf
1. �Cu�l es la diferencia entre una bacteria F + y una Hfr d. Las.pdf
 
1. �Cu�les de las siguientes afirmaciones sobre los or�genes de la a.pdf
1. �Cu�les de las siguientes afirmaciones sobre los or�genes de la a.pdf1. �Cu�les de las siguientes afirmaciones sobre los or�genes de la a.pdf
1. �Cu�les de las siguientes afirmaciones sobre los or�genes de la a.pdf
 
1. �Cu�l es la relaci�n entre Enron y SOX La quiebra y el esc�n.pdf
1. �Cu�l es la relaci�n entre Enron y SOX La quiebra y el esc�n.pdf1. �Cu�l es la relaci�n entre Enron y SOX La quiebra y el esc�n.pdf
1. �Cu�l es la relaci�n entre Enron y SOX La quiebra y el esc�n.pdf
 
1.) Imagina tres puntos en un mapa topogr�fico que est�n ubicados en.pdf
1.) Imagina tres puntos en un mapa topogr�fico que est�n ubicados en.pdf1.) Imagina tres puntos en un mapa topogr�fico que est�n ubicados en.pdf
1.) Imagina tres puntos en un mapa topogr�fico que est�n ubicados en.pdf
 
1. �Qu� es la dominancia apical 2. �Cu�l es el papel de la auxina.pdf
1. �Qu� es la dominancia apical 2. �Cu�l es el papel de la auxina.pdf1. �Qu� es la dominancia apical 2. �Cu�l es el papel de la auxina.pdf
1. �Qu� es la dominancia apical 2. �Cu�l es el papel de la auxina.pdf
 
1. �Por qu� no hubo un plan de sucesi�n en Lakkard Leather Carl F.pdf
1. �Por qu� no hubo un plan de sucesi�n en Lakkard Leather Carl F.pdf1. �Por qu� no hubo un plan de sucesi�n en Lakkard Leather Carl F.pdf
1. �Por qu� no hubo un plan de sucesi�n en Lakkard Leather Carl F.pdf
 
1. �Por qu� la nube es importante para ciudades como Dubuque mientra.pdf
1. �Por qu� la nube es importante para ciudades como Dubuque mientra.pdf1. �Por qu� la nube es importante para ciudades como Dubuque mientra.pdf
1. �Por qu� la nube es importante para ciudades como Dubuque mientra.pdf
 

Recently uploaded

MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

hello the code given is mostly complete but I need help with the Sol.pdf

  • 1. hello the code given is mostly complete but I need help with the Solver portion please Consider a maze made up of rectangular array of squares, such as the following one: X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X Figure 1--- A sample maze The X blocks represent a blocked square and form the walls of the maze. Let us consider mazes that have only one entrance and one exit, as in our example. Beginning at the entrance at the top left side of the maze, find a path to the exit at the bottom right side. You can move only up, down, left, or right. Square is either clear or blocked by an X character. Let a two-dimensional array represent the maze. Use a stack data structure to find a path through the maze. Some mazes might have more than one successful path, while others might have no path. Hints: The primary consideration is that if you reach a dead end, you need to be able to backtrack along the path to the point where you can try a different path. The stack data structure makes it possible to store the current path and backtrack if necessary. Every clear position visited in the current path is pushed to the stack and if a dead end is reached, the previous position is popped from the stack to backtrack. You need to have a loop that begins with the start position and pushes it into the stack then moves to a neighboring cell until either the goal position is reached, or the stack becomes empty. Make sure to mark each clear array cell you move to as visited to avoid checking it again and getting stuck in an infinite loop. For example, each array cell can have three different values: X for blocked, V for visited, and for clear. A dead end is an array cell whose all neighbors are either blocked or already visited. There are four files you should pay attention to: Position.java: a class to store the position of an array cell. It has two attributes: row and column along with their accessor and mutator methods. It also has an equals method that
  • 2. checks for equality of two Position objects. Maze.java: a class to store a maze. It has 3 attributes: a two-dimensional character array which represents the maze, a Position object to represent the start location, and another Position object to represent the stop location. MazeSolver: This class contains one static method, solve. It accepts a maze and returns an array of Positions that is used to traverse the maze if the maze is solvable. If the maze is not solvable then an empty array is returned. o Keep in mind that stacks store objects in reverse order so be sure to return the position array in the correct order. Tester: a sample driver class which calls the traverse method on a maze in either the SolvableMaze, UnsolvableMaze, or HugeSolvableMaze files. These should be at the root of the project folder SOLVER import java.util.Stack; public class MazeSolver { public static Position[] solve(Maze maze) { return null; } } POSITION public class Position { private int row; private int column; public Position(int row, int column) { this.row = row; this.column = column; } public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof Position)) { return false;
  • 3. } Position otherPosition = (Position) obj; return (otherPosition.row == row && otherPosition.column == column); } public String toString() { return "row:" + row + " column:" + column; } public int getRow() { return row; } public int getColumn() { return column; } } MAZE public class Maze {ate final char[][] maze; private final Position start, end; public Maze(char[][] maze, Position start, Position end) { this.maze = maze; if (validPosition(start)) { this.start = start; } else { throw new PositionNotValidException("The start position is valid for the maze: " + start); } if (validPosition(end)) { this.end = end; } else { throw new PositionNotValidException("The stop position is valid for the maze: " + end); } } public Position getStart() { return start; } public Position getEnd() { return end;
  • 4. } public int numRows() { return maze.length; } public int numCols(int row) { return maze[row].length; } public boolean validPosition(int row, int col) { if (row >= 0 && row < maze.length) { if (col >= 0 && col < maze[row].length) { return true; } } return false; } public boolean validPosition(Position pos) { return validPosition(pos.getRow(), pos.getColumn()); } public char getAt(Position pos) { if (validPosition(pos)) { return maze[pos.getRow()][pos.getColumn()]; } else { String msg = String.format("The position given is not valid: %s", pos.toString()); throw new PositionNotValidException(msg); } } public char getAt(int row, int column) { if (validPosition(row, column)) { return maze[row][column]; } else { String msg = String.format("The row and column given is not valid: row %d col %d", row, column); throw new PositionNotValidException(msg); } } public void setAt(Position pos, char c) {
  • 5. if (validPosition(pos)) { setAt(pos.getRow(), pos.getColumn(), c); } else { String msg = String.format("The position given is not valid: %s", pos.toString()); throw new PositionNotValidException(msg); } } public void setAt(int row, int column, char c) { if (validPosition(row, column)) { maze[row][column] = c; } else { String msg = String.format("The row and column given is not valid: row %d col %d", row, column); throw new PositionNotValidException(msg); } } public Maze clone() { char clone[][] = new char[maze.length][]; for (int r = 0; r < maze.length; r++) { clone[r] = new char[maze[r].length]; for (int c = 0; c < maze[r].length; c++) { clone[r][c] = maze[r][c]; } } return new Maze(clone, start, end); } public String toString() { StringBuffer sb = new StringBuffer(); for (int r = 0; r < maze.length; r++) { sb.append(maze[r]); sb.append("n"); } return sb.toString(); } } POSITIONEXCEPTION
  • 6. public class PositionNotValidException extends RuntimeException { public PositionNotValidException() { super(); } public PositionNotValidException(String msg) { super(msg); } private static final long serialVersionUID = 1L; } import java.io.File; import java.io.FileNotFoundException; import java.util.InputMismatchException; import java.util.Scanner; import maze.Maze; import maze.MazeSolver; import maze.Position; /** * Driver class to test students solution. The printed result should be a path * from the start to the finish where the path is represented by asterisks. * * The Solvable and Unsolvable mazes were generated using * https://www.dcode.fr/maze-generator * * */ public class Tester { private static Maze loadMaze(String file) { char maze[][] = null; Position start = null, stop = null; try { Scanner filein = new Scanner(new File(file)); // Load Header // First number is how many rows. // Second and third number are the row and column to start at. // Fourth and fifth number are the row and column to stop at.
  • 7. int row = filein.nextInt(); start = new Position(filein.nextInt(), filein.nextInt()); stop = new Position(filein.nextInt(), filein.nextInt()); filein.nextLine(); // End Header maze = new char[row][]; int currRow = 0; while (filein.hasNextLine()) { maze[currRow++] = filein.nextLine().replace("n", "").toCharArray(); } filein.close(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(1); } catch (Exception e) { System.out.println("Something bad happened. See exception message"); e.printStackTrace(); System.exit(2); } return new Maze(maze, start, stop); } private static void walkPath(Maze maze, Position traversal[]) { Position previous = null; for (Position p : traversal) { if (maze.getAt(p) == ' ') { maze.setAt(p, 'O'); } else if (maze.getAt(p) == 'O') { System.out.println("MISTAKE"); System.out.println("There is a repeated position " + p); System.exit(3); } else { System.out.println("MISTAKE"); System.out.println("There is an obstacle at position " + p); System.out.println(maze); System.exit(3); }
  • 8. // Check to make sure path is connected. if (previous != null) { int prevRow = previous.getRow(); int prevCol = previous.getColumn(); int curRow = p.getRow(); int curCol = p.getColumn(); boolean isPathConnected = false; if (curRow - 1 == prevRow || curRow + 1 == prevRow) { isPathConnected = curCol == prevCol; } else if (curCol - 1 == prevCol || curCol + 1 == prevCol) { isPathConnected = curRow == prevRow; } if (!isPathConnected) { System.out.println("Path not connected"); System.out.println("From: " + previous); System.out.println("To: " + p); maze.setAt(previous, '?'); maze.setAt(p, '?'); System.out.println(maze); System.exit(3); } } previous = p; } } private static void printDialog() { System.out.println("Pick an option"); System.out.println("1: Solvable Maze"); System.out.println("2: Unsolvable Maze"); System.out.println("3: Huge Unsolvable Maze"); System.out.println("4: EXIT"); } private static int getChoice(Scanner in) { boolean exit = false; int choice = 0; do {
  • 9. try { System.out.print(">> "); choice = Integer.parseInt(in.nextLine()); if (choice > 0 && choice <= 4) { exit = true; } else { System.out.println("Choice must be either 1, 2, 3, or 4."); } } catch (InputMismatchException e) { System.out.println("Choice must be either 1, 2, 3, or 4."); } } while (!exit); return choice; } public static void main(String[] args) { Maze clone; Position solution[]; Scanner userIn = new Scanner(System.in); boolean exit = false; while (!exit) { printDialog(); int choice = getChoice(userIn); switch (choice) { case 1: /** Solvable Maze ***/ Maze solvableMaze = loadMaze("SolvableMaze"); clone = solvableMaze.clone(); System.out.println("Testing Solvable Maze"); System.out.println("Starts at " + clone.getStart()); System.out.println("Ends at " + clone.getEnd()); System.out.println(clone); solution = MazeSolver.solve(clone); if (solution.length != 0) { walkPath(solvableMaze, solution); System.out.println("nSOLUTION"); System.out.println(solvableMaze);
  • 10. } else { System.out.println("Null returned but maze is solvable.n"); } break; /***************************************************************************** **/ case 2: /** Unsolvable Maze **/ Maze unsolvableMaze = loadMaze("UnsolvableMaze"); clone = unsolvableMaze.clone(); System.out.println("Testing Unsolvable Maze"); System.out.println(clone); solution = MazeSolver.solve(clone); if (solution.length == 0) { System.out.println("CORRECT"); System.out.println("This maze is unsolvable so an empty array should be returned."); } else { System.out.println("INCORRECT"); System.out.println("This maze is unsolvable. An empty array should be returned."); } break; /***************************************************************************** ***/ /** Huge Solvable Maze **/ case 3: Maze hugeSolvableMaze = loadMaze("HugeSolvableMaze"); clone = hugeSolvableMaze.clone(); System.out.println("Testing Huge Solvable Maze"); System.out.println("Starts at " + clone.getStart()); System.out.println("Ends at " + clone.getEnd()); System.out.println(clone); solution = MazeSolver.solve(clone); if (solution.length != 0) { walkPath(hugeSolvableMaze, solution); System.out.println("nSOLUTION");
  • 11. System.out.println(hugeSolvableMaze); } else { System.out.println("Null returned but maze is solvable.n"); } break; case 4: exit = true; } } System.out.println("Exitting!"); } }