function B = conway(A)
%CONWAY One generation of Conway's Game of Life.
%  B = CONWAY(A) computes the next generation B starting from
%  the current generation A using the rules of Conway's
%  Game of Life.
%
%  A is a 2-dimensional array of values where the value
%  0 indicates that the cell is dead, and any other value indicates
%  that the cell is alive.

[rows, cols] = size(A);
B = zeros(rows, cols);
for r = 1:rows
    for c = 1:cols
        n = alive(A, r, c);
        if A(r, c) == 0
            if n == 3
                B(r, c) = 1;
            end
        else
            if n < 2
                B(r, c) = 0;
            elseif n < 4
                B(r, c) = 1;
            else
                B(r, c) = 0;
            end
        end
    end
end

end


function n = alive(A, row, col)
%ALIVE Number of neighbours that are alive.
%  N = ALIVE(A, ROW, COL) returns the number of neighbours
%  that are alive surrounding the cell A(ROW, COL)

[nRows, nCols] = size(A);
startRow = max([row - 1, 1]);
stopRow = min([row + 1, nRows]);
startCol = max([col - 1, 1]);
stopCol = min([col + 1, nCols]);
neighbourhood = A(startRow:stopRow, startCol:stopCol);
n = sum(neighbourhood(:) > 0);
if A(row, col) > 0
  n = n - 1;
end

end
