Hey mbozzi so my assignment restricts creating other functions and using other functions other than the ones that we have been given. |
Usually restrictions like this apply only to the interface. Are you sure it's not acceptable to add private or internal functions available for the implementation's use only?
Restricting changes to the interface is a useful and realistic exercise, but restricting changes to the implementation is unrealistic -- decomposing problems into smaller ones is absolutely fundamental to handling complexity in software. It is critical to writing code that works correctly, is maintainable, and robust. A restriction against decomposing problems is actively destructive to your ability to solve problems and to your programming skill. Say it ain't so. Every design book I have ever read agrees with me.
Anyways:
0. You're in danger of running off the edge of the board. What happens if a live cell appears at index 0 on any axis while computing the number of adjacent living cells? The only way I can see this setup working is if you can guarantee that
i
and
j
will never be the last or first element of any of the arrays.
1. The number of adjacent cells never gets reset. You'll have to compute the number of adjacent cells for
any cell, not just the living ones, and then compute the next state of any given cell depending on
a.) it's state
b.) the number of living adjacent cells.
Assuming that getState() return true, the large if-chain on lines [7, 38] can be shortened -- just sum the conditions. If there is a doubt that it returns a boolean (as there may be; it's poorly named), normalize them:
1 2 3 4 5 6 7 8 9
|
adjAlive =
!!currentLife[i + 1][j + 1].getState() +
!!currentLife[i + 1][j ].getState() +
!!currentLife[i + 1][j - 1].getState() +
!!currentLife[i ][j + 1].getState() +
!!currentLife[i ][j - 1].getState() +
!!currentLife[i - 1][j + 1].getState() +
!!currentLife[i - 1][j ].getState() +
!!currentLife[i - 1][j - 1].getState();
|
Note: I couldn't work out whether or not there was a typo in the if-chain, so I just wrote it out.
The
!!
is double negation, a common-ish shortcut for converting something to a boolean. The trick is useful exactly in cases like this.
Psuedocode:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
for (int i = 0; i < MAX_BOARD; ++i)
for (int j = 0; j < MAX_BOARD; ++j) {
// reset me every iteration
adjLiving = compute_adjacent_living_cells();
Cell currentCell = currentLife[i][j];
if (currentCell.getState()) { // if the current cell is alive
if (adjLiving < 2) currentCell.setState(dead); // die from underpopulation
if (adjLiving == 3) currentCell.setState(live); // remain alive
else currentCell.setState(dead); // die from overpopulation
} else if(adjLiving == 3) {
currentCell.setState(live); // become alive from reproduction
}
// now copy the adjusted cell to the next generation:
nextLife[i][j] = currentCell;
}
}
|