Solution to Mazer free response practice question6

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[row].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;
}
```

6 thoughts on “Solution to Mazer free response practice question”

1. Matthew Driben

Wouldn’t the String composed of backslashes be “\\\\” instead of “\\” because two backslashes are required to form one backslash? Isn’t the backslash an escape operator? Thank you.

• Brandon Horn

Yes, the backslash character is an escape operator.

The string `"\\"` would be displayed as a single backslash if printed. That’s why I used `"\\"` for the backslash and `"/"` for the forward slash.

• Matthew Driben

Oh, OK. I did not realize your intent when I read through the problem, then.

• Brandon Horn

A real AP problem would probably be more explicit about something like that.

2. Anonymous

Couldn’t you have in part a in the for loop instead of putting the “maze.length” put “rows”?

• Brandon Horn

Yes.