Other 2004 FR Questions FR other years Be Prepared Home
A-3
Part (a)
  // postcondition: returns the minimum number of fish that need to be 
  //                added to make the population density greater than
  //                minDensity
  private int numUnder()
  {
    int current = theEnv.numObjects();
    int cells = theEnv.numRows() * theEnv.numCols();

    int needed = 0;
    while ((double)(current + needed) / cells  <= minDensity)
      needed++; 1

    return needed;
  }
Notes:
  1. This solution is preferred if you really want to save mental energy and play it safe.  Efficiency does not matter on the AP exam, unless specifically requested.  Perhaps a little more elegant would be:
        needed = (int)(minDensity * cells) + 1 - current;
        if (needed < 0) needed = 0;

Part (b)
  //  postcondition: returns a random location within the bounds of theEnv
  private Location randomLocation()
  {
    Random gen = RandNumGenerator.getInstance(); 1
    int rows = theEnv.numRows();
    int cols = theEnv.numCols();
    return new Location(gen.nextInt(rows), gen.nextInt(cols));
  }
Notes:
  1. Using
        Random gen = new Random();
    or using Math.random() is likely to cause lost points.

Part (c)
  // precondition:  0 <= numToAdd <= number of empty locations in theEnv
  // postcondition: the number of fish in theEnv has been increased
  //                by numToAdd; the fish added are placed at
  //                random empty locations in theEnv
  public void addFish(int numToAdd)
  {
    while (numToAdd > 0)
    {
      Location loc = randomLocation();
      if (theEnv.isEmpty(loc))
      {
        new Fish(theEnv, loc); 1
        numToAdd--;
      }
    }
  }
Notes:
  1. The Fish constructor adds the fish to theEnv.  If you write
       theEnv.add(new Fish(theEnv, loc));
    theEnv.add will throw an IllegalArgumentException, because loc will have been already occupied.

Other 2004 FR Questions | Back to Contents

Copyright © 2004 by Skylight Publishing
support@skylit.com