康威的生命游戏错误的邻居很重要

时间:2017-11-10 05:07:21

标签: matlab conways-game-of-life

我一直在搞乱Conway的生命游戏的初始化,我遇到了一些问题。我不能为我的生活弄清楚为什么“活着的邻居粒子”(我称之为'positionSum')的数量没有被正确统计。我有以下MATLAB代码。

我从一个简单的3x3网格开始,让我的代码正常工作。

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)  

使用这个过程我相信我的总数不正确。

对于左上方带有白色的3x3棋盘格(如here所示),我得到以下数据:

4  5  4
5  4  5
4  5  4

1 个答案:

答案 0 :(得分:0)

我不确定您为northeastsouthwest选择这些数组的原因。一种更简单的方法是对矩阵的边界进行填零,然后添加移位版本。

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