Complete the Aquarium practice problem before reviewing the solution.
Review the Droppy solution with AP CS Tutor Brandon Horn.
Part (a) findTank
method
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) addFish
method
public ArrayList<Fish> addFish(ArrayList<Fish> fishes)
{
ArrayList<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) addTank
method
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;
}