Other 2007 FR Questions FR other years Be Prepared Home
AB-4
Part (a)
  /** Precondition: hasNext() returns true
   *  Postcondition: loc has been updated to the successor location
   *  @return the next location in the environment
   */
  public Location next()
  {
    int row = loc.row();
    int col = loc.col();
    Location oldLoc = loc;

    if (row == env.numRows() - 1)
      loc = new Location(col + 1, env.numCols() - 1);
    else if (col == 0)
      loc = new Location(0, row + 1);
    else
      loc = new Location(row + 1, col - 1);

    return oldLoc;
  } 
Notes:
  1. Alternative solution:
      public Location next()
      {
        int row = loc.row();
        int col = loc.col();
    
        if (row == env.numRows() - 1)
        {
          row = col + 1;
          col = env.numCols() - 1;
        }
        else if (col == 0)
        {
          col = row + 1;
          row = 0;
        }
        else
        {
          row++;
          col--;
        }
    
        Location oldLoc = loc;
        loc = new Location(row, col);
    
        return oldLoc;
      }

Part (b)
  /** @param env the environment over which to iterate
   *         Precondition: env is square, i.e., env.numRows() == env.numCols()
   *  @param n the desired number of empty locations to be returned
   *         Precondition: n > 0
   *  @return a list of the first n empty locations;
   *          all empty locations if there are fewer than n empty locations.
   *          Locations are ordered in the order in which they are visited by the  EnvIterator
   */
  public List emptyLocs(BoundedEnv env, int n)
  {
    List<Location> emptyLocs = new LinkedList<Location>(); 1
    Iterator<Location> it = new EnvIterator(env);
    int count = 0;

    while (count < n && it.hasNext())
    {
      Location loc = it.next(); 2
      if (env.isEmpty(loc))
      {
        emptyLocs.add(loc);
        count++;
      }
    }

    return emptyLocs;
  }
Notes:
  1. Or new ArrayList<Location>();.

  2. Call it.next() only once within the loop.

Other 2007 FR Questions | Back to Contents

Copyright © 2007 by Skylight Publishing
support@skylit.com