Solution to Aquarium free response practice question

Complete the Aquarium practice problem before reviewing the solution.

Review the Aquarium solution with AP CS Tutor Brandon Horn.

Part (a)

private Tank findTank(Fish fishy)
 {
  for (Tank tank : tanks)
  {
   boolean suitable = tank.temp() >= fishy.minTemp()
     && tank.temp() <= fishy.maxTemp();

   for (Fish fish : tank.getFish())
    if (!fish.isCompatible(fishy))
     suitable = false;

   if (suitable)
    return tank;
  }

  return null;
 }

Part (b)

public List <Fish> addFish(List<Fish> fishes)
 {
  List<Fish> cannotAdd = new ArrayList<Fish>();

  for (Fish fish : fishes)
  {
   Tank tank = findTank(fish);

   if (tank != null)
    tank.addFish(fish);
   else
    cannotAdd.add(fish);
  }

  return cannotAdd;
 }

Part (c)

public boolean addTank(Tank fishTank)
 {
  if (tanks.size() == 0 || Math.abs(tanks.get(0).temp() - fishTank.temp()) <= 5)
  {
   tanks.add(0, fishTank);
   return true;
  }

  if (Math.abs(tanks.get(tanks.size() - 1).temp() - fishTank.temp()) <= 5)
  {
   tanks.add(fishTank);
   return true;
  }

  for (int i = 1; i < tanks.size(); i++)
  {
   int leftTemp = tanks.get(i - 1).temp();
   int rightTemp = tanks.get(i).temp();

   if (Math.abs(leftTemp - fishTank.temp()) <= 5
     && Math.abs(rightTemp - fishTank.temp()) <= 5)
   {
    tanks.add(i, fishTank);
    return true;
   }
  }

  return false;
 }

Get AP CS Help

Leave a Reply