Complete the Mazer practice problem before reviewing the solution.
Review the Mazer
solution with AP CS Tutor Brandon Horn.
Part (a)
public Mazer(int rows, int cols)
{
maze = new String[rows][cols];
for(int row = 0; row < maze.length; row++)
{
for(int col = 0; col < maze[0].length; col++)
{
if(col == 0 || maze[row][col - 1] == null)
{
double randNum = Math.random();
if(randNum < 0.1)
maze[row][col] = "|";
else if(randNum < 0.3)
maze[row][col] = "/";
else if(randNum < 0.5)
maze[row][col] = "\\";
}
}
}
}
Part (b)
public boolean willWin(int startRow)
{
int playerRow = startRow;
for(int playerCol = 0; playerCol < maze[0].length; playerCol++)
{
String obstacle = maze[playerRow][playerCol];
if(obstacle != null)
{
if(obstacle.equals("|"))
return false;
else if(obstacle.equals("\\"))
playerRow++;
else if(obstacle.equals("/"))
playerRow--;
if(playerRow < 0 || playerRow >= maze.length)
return false;
}
}
return true;
}
Additional 2D array resources
- Intro to 2D arrays
- 2D array exercises
- Droppy FR
- Flight FR
- MatrixManipulator exercise
- DeterminantFinder exercise
Help & comments
Get help from AP CS Tutor Brandon Horn
Comment on Mazer free response
2024-04-15
“I dont understand why we need a col==0
in ppart of the boolean expression.”
Response
The expression: maze[row][col - 1] == null
throws an ArrayIndexOutOfBoundsException
when col == 0
.
The expression: col == 0 || maze[row][col - 1] == null
evaluates to true
when col == 0
. See Short circuit evaluation of boolean expressions for additional discussion and examples.