Open alexey-malov opened 9 years ago
Состояния поля лучше назвать не dead и alive, а empty и occupied
int GetNeighboursCount(CellsField const &field, int x, int y)
{
int count = 0;
for (int curY = y - 1; curY <= y + 1; curY++)
{
for (int curX = x - 1; curX <= x + 1; curX++)
{
if (IsValidCell(curX, curY, field.width, field.height) // the cell must be valid (not a wall)
&& !((curY == y) && (curX == x)) // do not count analyzed cell
&& (field.cells[curY][curX] == ALIVE)) // the cell must be alive
{
count++;
}
}
}
return count;
}
Рассмотреть альтернативу в виде 8 вызовов функции:
return
GetLifeCellCount(field, x - 1, y - 1) +
GetLifeCellCount(field, x + 0, y - 1) +
GetLifeCellCount(field, x + 1, y - 1) +
GetLifeCellCount(field, x - 1, y + 0) +
GetLifeCellCount(field, x + 1, y + 0) +
GetLifeCellCount(field, x - 1, y + 1) +
GetLifeCellCount(field, x + 0, y + 1) +
GetLifeCellCount(field, x + 1, y + 1);
или
auto GetLifeCellCount = [&field](int x, int y)
{
return GetCellState(field, x, y) == CellState::Occupied ? 1 : 0;
};
return
GetLifeCellCount(x - 1, y - 1) +
GetLifeCellCount(x + 0, y - 1) +
GetLifeCellCount(x + 1, y - 1) +
GetLifeCellCount(x - 1, y + 0) +
GetLifeCellCount(x + 1, y + 0) +
GetLifeCellCount(x - 1, y + 1) +
GetLifeCellCount(x + 0, y + 1) +
GetLifeCellCount(x + 1, y + 1);
либо использовании GetLifeCellCount внутри цикла
150*0,8=120
void SetCell(CellsField &field, int x, int y, CellState value)
{
field.cells[GetVectorPosition(x, y, field.width)] = value;
}
Лучше добавить проверку на выход за пределы массива. Возможные способы обработки: бросасть исключение ничего не делать *"оборачивать" (выход за левую границу приводит к обращению к правым клеткам)
150*0,95 = 142,5
Вместо malloc-ов лучше используй new, а еше лучше vector для хранения элементов. Ну и вспомогательные функции для доступа к элементам поля
Есть Visual Leak Detector. Выводит в консоль сведения об обнаруженных утечках памяти:
http://vld.codeplex.com