
% Homework 4
% computeNextState.m
% CS 1109, Summer 2011
% July 18
%
% This script reads the current state of the Game of Life board from the
% matrices blueCells and redCells, computes the next state of every cell
% on the board, and writes this information to the matrices nextBlueCells
% and nextRedCells
%

% Get the size of the board
[numRows numCols] = size(blueCells);

% We only compute the next state of the cells that are not on the edge of
% the board, since these just stay dead all the time
for x = 2 : numRows - 1
    for y = 2 : numCols - 1
        
        % Begin by computing the number of blue and red neighbors of the
        % cell at position (x, y).
        blueSum = sum(sum(blueCells(x-1:x+1, y-1:y+1))) - blueCells(x, y);
        redSum = sum(sum(redCells(x-1:x+1, y-1:y+1))) - redCells(x, y);
              
        % This is the total number of neighbors (of either tribe)
        numLiveCells = blueSum + redSum;
        
        % If a cell has exactly three live neighbors, it either converts to
        % the tribe of the majority (if already alive), or is born into the
        % tribe of the majority (if currently dead).
        if (numLiveCells == 3)
            if (blueSum > redSum)
                nextBlueCells(x, y) = 1;
                nextRedCells(x, y) = 0;
            else
                nextBlueCells(x, y) = 0;
                nextRedCells(x, y) = 1;
            end
        % If a cell has exactly two live neighbors, its state is unchanged
        % after the next time step (i.e., it either stays dead, or stays
        % alive as appropriate
        elseif (numLiveCells == 2)
            nextBlueCells(x, y) = blueCells(x, y);
            nextRedCells(x, y) = redCells(x, y);
        % In all other cases (i.e., either < 2 or > 3 neighbors), the cell
        % dies
        else            
            nextBlueCells(x, y) = 0;
            nextRedCells(x, y) = 0;
        end
        
    end
end

% Common mistakes / other observations:
%
% 1) Almost everyone submitted correct programs for this problem, though
% some solutions were more verbose than others. One particular thing to
% note is how a nested use of the sum function was used to compactly add
% up all the elements of a matrix. There are other ways to do this
% including:
%
%    - Explicitly adding up all 8 neighboring cells, as blueCells(x-1,y-1)
%      + blueCells(x-1,y) + ... + blueCells(x+1, y+1).
%    - Using a nested for-loop
%
% 2) Observe how via careful reinterpretation of the game rules, we were
% able to distill the original 6 rules down to just 3. You should always
% strive to find such ``refactorings'' of code that preserve the meaning of
% the code while making the solution more efficient and readable.
%

