Java Reference
In-Depth Information
Code 10.3
continued
Part of the Simulator
class
for ( int row = 0; row < field.getDepth(); row++) {
for ( int col = 0; col < field.getWidth(); col++) {
if (rand.nextDouble() <= FOX_CREATION_PROBABILITY) {
Location location = new Location(row, col);
Fox fox = new Fox(true, field, location);
foxes.add(fox);
}
else if (rand.nextDouble() <=
RABBIT_CREATION_PROBABILITY) {
Location location = new Location(row, col);
Rabbit rabbit = new Rabbit( true , field, location);
rabbits.add(rabbit);
}
// else leave the location empty.
}
}
}
// other methods omitted
}
The Simulator has three important parts: its constructor, the populate method, and the
simulateOneStep method. (The body of simulateOneStep is shown below.)
When a Simulator object is created, all other parts of the simulation are constructed by it
(the field, the lists to hold the different types of animals, and the graphical interface). Once all
these have been set up, the simulator's populate method is called (indirectly, via the reset
method) to create the initial populations. Different probabilities are used to decide whether a
particular location will contain one of these animals. Note that animals created at the start of the
simulation are given a random initial age. This serves two purposes:
It represents more accurately a mixed-age population that should be the normal state of the
simulation.
If all animals were to start with an age of zero, no new animals would be created until the ini-
tial population had reached their respective breeding ages. With foxes eating rabbits regard-
less of the fox's age, there is a risk that either the rabbit population will be killed off before it
has a chance to reproduce or that the fox population will die of hunger.
Exercise 10.22 Modify the populate method of Simulator to determine whether set-
ting an initial age of zero for foxes and rabbits is always catastrophic. Make sure that you run it
a sufficient number of times—with different initial states, of course!
Exercise 10.23 If an initial random age is set for rabbits but not foxes, the rabbit population will
tend to grow large while the fox population remains very small. Once the foxes do become old enough
to breed, does the simulation tend to behave again like the original version? What does this suggest
about the relative sizes of the initial populations and their impact on the outcome of the simulation?
 
Search WWH ::




Custom Search