The key part of the simulator is the inner loop that builds a new generation from the current generation . Recall that the current generation will be represented by an array named g, and the next generation by an array ng.
Let n be the number of individuals in g. In the early stages of the simulation n will be the same as k, the carrying capacity, since all individuals in a new generation will survive. Toward the end of the simulation n will be smaller than k.
Recall also that on average each individual is able to reproduce r times, where r is reproductive factor, another one of the input parameters. A population of n individuals will thus produce, on average, offspring.
To create the next generation, we need to simulate the creation of individuals, add new mutations to the individuals, and then select k random survivors to form the new generation. If the number of survivors is less than k, then all survivors go into the new generation. Extinction will occur when none of the new offspring survive.