Other 2009 FR Questions FR other years Be Prepared Home
AB-2
Part (a)
  // Part (a)

  /** Moves this critter to the given location loc or removes this critter
   *  from its grid if loc is null. Increments the count for location loc if and only if
   *  moving to loc from a different location and loc is not null.
   *  Postcondition: (1) getLocation() == loc.
   *  (2) The state of all actors other than those at the old and new locations is unchanged.
   *  @param loc the location to move to
   */
  public void makeMove(Location loc)
  {
    Location oldLoc = getLocation();
    super.makeMove(loc);

    if (loc != null && !oldLoc.equals(loc))
    {
      if (places.containsKey(loc))
      {
        int count = places.get(loc).intValue();
        places.put(loc, new Integer(count + 1)); 1
      }
      else
      {
        places.put(loc, new Integer(1));
      }
    }
  }
Notes:
  1. Or simply, relying on autoboxing/unboxing:
        int count = places.get(loc);
        places.put(loc, count + 1);
    

Part (b)
  /** Precondition: this Historian has changed its location at least once.
   *  @return a list containing the location(s) this Historian
   *          has moved to most frequently.
   */
  public List<Location> mostPopularPlaces()
  {
    Set<Location> visited = places.keySet();
    int maxVisits = 0;

    for (Location loc : visited)
    {
      int count = places.get(loc).intValue(); 1
      if (count > maxVisits)
        maxVisits = count;
    }

    List<Location> mostVisited = new LinkedList<Location>(); 2

    for (Location loc : visited)
    {
      int count = places.get(loc).intValue();
      if (count == maxVisits)
        mostVisited.add(loc);
    }

    return mostVisited;
  }
Notes:
  1. Or simply, relying on autoboxing/unboxing:
        int count = places.get(loc);
    
  2. Or: new ArrayList<Location>();

Other 2009 FR Questions | Back to Contents

Copyright © 2009 by Skylight Publishing
support@skylit.com