Part (a)
// a juvenile Salmon chooses its next location as if it were
// an ordinary fish;
// a mature salmon chooses an empty neighboring location that is
// closer to home than this fish's current location, if one exists;
// otherwise, it returns this fish's current location
// postcondition: the state of this Salmon is unchanged
protected Location nextLocation()
{
if (age < matureAge)
return super.nextLocation();
if (location().equals(homeLocation))
return location();
ArrayList emptyNbrs = emptyNeighbors();
int k = 0; 1
while (k < emptyNbrs.size())
{
Location loc = (Location)emptyNbrs.get(k);
if (distanceHome(loc) >= distanceHome(location()))
emptyNbrs.remove(k);
else
k++;
}
if (emptyNbrs.size() == 0)
return location();
Random randNumGen = RandNumGenerator.getInstance();
int randNum = randNumGen.nextInt(emptyNbrs.size());
return (Location) emptyNbrs.get(randNum);
}
Notes:
- The question says that a mature salmon can move to any
neigboring location that is closer to home.
In the spirit of the Case Study, the following code chooses such
location randomly by first eliminating all locations from the
emptyNbrs list that are not closer. (Be careful not to use a for loop here.)
But choosing the first closer-to-home location in the list would be fine, too.
For example:
for (int k = 0; k < emptyNbrs.size(); k++)
if (distanceHome((Location)emptyNbrs.get(k)) < distanceHome(location()))
return (Location)emptyNbrs.get(k);
return location();
It would be a waste of time and effort to try to choose a location that
is the closest to home. If the distance is defined as the number
of moves needed to reach home, there can be at most two locations in
emptyNbrs that are closer to home and their distances from home
are the same.
Part (b)
// acts for one step of the simulation
public void act()
{
if (!isInEnv())
return;
if (age < matureAge || !location().equals(homeLocation))
move();
else if (breed())
die();
age++; 1
}
Notes:
- It is a little awkward that fish's age is incremented
even after it dies. But it makes the code a little shorter...
|