Other 2007 FR Questions FR other years Be Prepared Home
AB-2
Part (a)
  /** Initializes and fills personMap so that each Person in personList is a key,
   *  and the value associated with each key k is a PriorityQueue of Pair objects
   *  pairing k with all other Persons in  personList
   *  @param personList a nonempty list of Person objects
   */
  public PairMatcher(List personList)
  {
    personMap = new HashMap<Person, PriorityQueue<Pair>>(); 1
    for (Person p : personList)
    {
      PriorityQueue<Pair> q = new PriorityQueue<Pair>();
      for (Person p2 : personList)
        if (p2 != p) 2
          q.add(new Pair(p, p2));
      personMap.put(p, q);
    }
  }
Notes:
  1. Use a HashMap because we are told that Person has a hashCode method.  For a TreeMap, Person would have to implement Comparable.

  2. In this case we are checking whether this is exactly the same Person object, not just an equal one: we don't know whether equal Persons are allowed in the list.

Part (b)
  /** @param p the Person to be matched
   *  @param num the number of Person objects to remove
   *         Precondition: if p is in personMap, then num is > 0 and less than or equal to
   *                       the number of pairs in the priority queue associated with p
   *  @return an array of the num removed Person objects;
   *          null if p is not in  personMap
   */
  public Person[] removeNumMatches(Person p, int num)
  {
    if (!personMap.containsKey(p))
      return null;
    PriorityQueue<Pair> q = personMap.get(p); 1

    Person[] arr = new Person[num];

    for (int i = 0; i < num; i++)
      arr[i] = q.remove().getPerson2();

    return arr;
  }
Notes:
  1. Or:
        PriorityQueue<Pair> q = personMap.get(p);
        if (q == null)
          return null;

Other 2007 FR Questions | Back to Contents

Copyright © 2007 by Skylight Publishing
support@skylit.com