Other 2006 FR Questions FR other years Be Prepared Home
A-4
Part (a)
  // returns null if no empty locations in column;
  // otherwise, returns the empty location with the
  // largest row index within the specified column;
  // precondition: 0 <= column < theEnv.numCols()
  public Location dropLocationForColumn(int column)
  {
    int maxRow = -1; 1

    for (int row = 0; row < theEnv.numRows(); row++)
      if (theEnv.isEmpty(new Location(row, column)))
        maxRow = row;

    if (maxRow < 0)
      return null;

    return new Location(maxRow, column); 2
  }
Notes:
  1. Although other approaches are possible, the easiest one is probably to treat this as traversing an array and finding a maximum value that satisfies a certain condition.

  2. Not return maxRow!

Part (b)
  // returns true if dropping a piece of the given color into the
  // specified column matches color with three neighbors;
  // otherwise, returns false
  // precondition: 0 <= column < theEnv.numCols()
  public boolean dropMatchesNeighbors(int column, Color pieceColor)
  {
    Location dropLoc = dropLocationForColumn(column);
    if (dropLoc == null) 1
      return false;
    ArrayList nbrs = theEnv.neighborsOf(dropLoc);

    int count = 0;

    for (int index = 0; index < nbrs.size(); index++)
    {
      Location loc = (Location)nbrs.get(index);
      Piece piece = (Piece)theEnv.objectAt(loc);
      if (piece != null && piece.color().equals(pieceColor)) 2
        count++;
    }

    return count == 3;
  }
Notes:
  1. Even though you cannot find a winning location in a full column, you still need this check to avoid a NullPointerException in neighborsOf.

  2. Be careful: piece can be null, in which case you don't want to call its methods.

Other 2006 FR Questions | Back to Contents

Copyright © 2006 by Skylight Publishing
support@skylit.com