0

I've been messing around with the initialisation of Conway's Game of Life and I'm running into some problems. I can't for the life of me figure out why the number of 'alive neighbour particles' (I'm calling this 'positionSum') isn't being counted correctly. I have the following MATLAB code.

I'm starting with a simple 3x3 grid to get my code working.

R = 3; C = 3; % row and column numbers

X = rand(R, C); % generates random grid
Y = X < 0.5;  % creates array of logicals
A = Y;

imshow(Y, 'InitialMagnification', 'fit') % shows initial cell configuration

north = [R, 1:R-1];  % north neighbour
east = [2:C, 1];     % east neighbour
south = [2:R, 1];    % south neighbour
west = [C, 1:C-1];   % west neighbour

% gives the total number of live neighbours
positionSum = A(north, :) + A(south, :) + A(:, east) + A(:, west) ...
+ A(north, east) + A(north, west) + A(south, east) + A(south, west)  

Using this process I believe I'm getting incorrect totals.

For a 3x3 checkerboard with white in the upper left (as seen here) I get the following counts:

4  5  4
5  4  5
4  5  4
Wolfie
  • 27,562
  • 7
  • 28
  • 55
Enroy
  • 17
  • 3
  • Just thought I'd link [this](https://stackoverflow.com/a/3514906/52738) here. You might find it interesting. – gnovice Nov 11 '17 at 04:48

1 Answers1

0

I'm not sure why you've chosen those arrays for north,east,south, orwest. An easier way would be to zero-pad the border of your matrix, then add shifted versions.

A = randi([0,1], 3, 3); % Initialise random 0/1 matrix
% Timestep loop for Game of Life
numsteps = 10;
for ii = 1:numsteps
    % Create total matrix which has a border of 0s compared to A
    % Meaning it's 2 bigger in each dimension
    temp = zeros(size(A)+2);
    % Add in 4 directions. Middle A-sized region of temp is temp(2:end-1,2:end-1)
    temp(1:end-2, 2:end-1) = temp(1:end-2, 2:end-1) + A; % Shift A up
    temp(3:end,   2:end-1) = temp(3:end,   2:end-1) + A; % Shift A down
    temp(2:end-1, 1:end-2) = temp(2:end-1, 1:end-2) + A; % Shift A left
    temp(2:end-1, 3:end)   = temp(2:end-1, 3:end)   + A; % Shift A right
    % Continue for diagonal neighbours
    % temp(...

    % Extract number of neighbours from middle region of temp
    neighbs = temp(2:end-1, 2:end-1);
    % Continue with chosen GoL rules now we have neighbours
    % ...
    % A = ...
end
Wolfie
  • 27,562
  • 7
  • 28
  • 55