Solution to Mazer free response practice question 6

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;
}

Get AP CS Help

6 thoughts on “Solution to Mazer free response practice question

  1. Reply Matthew Driben Apr 27,2016 10:45 am

    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.

    • Reply Brandon Horn Apr 27,2016 4:26 pm

      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.

  2. Reply Anonymous Apr 30,2016 10:23 am

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

Leave a Reply