challenge ライフゲーム

セルオートマトンに関するお題です. 
2次元タイプの'ライフゲーム'を実装して下さい. 
初期値としては10行10列程度の格子上の平面に0.3程度の人口(?)密度を考え, 
末端はループするようにして下さい. (例: 座標[-1, -1] = [10, 10])

それだけだと簡単すぎると思われる方は, 
過密状態で間引きが発生するような機能を組み込んで下さい. 
間引きは, 少なくともその後の1時間ステップにおける死亡率が, 
それをしなかった場合よりも小さくなれば結構です. 
(死亡率の最小化は複雑性が高すぎる感がありますし. )
サンプル:
t = 0
[ ][*][ ][ ][ ][ ][*][*][*][ ]
[ ][ ][ ][ ][*][ ][ ][*][*][ ]
[ ][ ][ ][*][ ][ ][*][ ][*][ ]
[*][ ][*][*][ ][ ][*][ ][ ][ ]
[ ][*][ ][ ][ ][ ][ ][ ][*][ ]
[*][ ][ ][ ][*][ ][*][*][ ][*]
[ ][*][ ][ ][ ][ ][*][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][*]
[*][ ][ ][ ][ ][ ][*][ ][ ][*]
[ ][ ][ ][ ][*][*][ ][ ][*][ ]
t = 1
[ ][ ][ ][ ][*][ ][ ][ ][ ][*]
[ ][ ][ ][ ][ ][*][ ][ ][ ][*]
[ ][ ][*][ ][*][*][*][ ][*][*]
[ ][*][ ][*][ ][ ][ ][ ][ ][*]
[ ][ ][*][*][ ][*][*][ ][*][ ]
[ ][*][ ][ ][ ][*][*][ ][*][*]
[ ][ ][ ][ ][ ][*][*][*][*][*]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][*]
[*][ ][ ][ ][ ][*][ ][ ][*][ ]
[*][ ][ ][ ][ ][ ][ ][ ][ ][ ]

Posted feedbacks - Nested

Flatten Hidden

C#で書いてみました。特に「間引き」の処理は入れていません。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;

public class LifeGame {
    private int time_ = 0;
    private readonly bool[][] matrix_;

    public LifeGame(int rows, int cols) {
        Random random = new Random();
        matrix_ = new bool[rows][];
        for (int rowIndex = 0; rowIndex < rows; rowIndex++) {
            matrix_[rowIndex] = new bool[cols];
            for (int index = 0; index < cols; index++) {
                if (random.NextDouble() < 0.3) {
                    matrix_[rowIndex][index] = true;
                }
            }
        }
    }

    public int Time {
        get {
            return time_;
        }
    }
    public String GetDisplayMatrix() {
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        foreach (bool[] row in matrix_) {
            foreach (bool cell in row) {
                builder.AppendFormat("[{0}]", cell? "*": " ");
            }
            builder.Append('\n');
        }
        return builder.ToString();
    }


    public void NextStep() {
        bool[][] oldMatrix = CopyMatrix(matrix_);
        for (int rowIndex = 0; rowIndex < matrix_.Length; rowIndex++) {
            for (int colIndex = 0; colIndex < matrix_[rowIndex].Length; colIndex++) {
                matrix_[rowIndex][colIndex] = Next(rowIndex, colIndex, oldMatrix);
            }
        }
        time_++;
    }
    private bool[][] CopyMatrix(bool[][] matrix) {
        bool[][] result = new bool[matrix.Length][];
        for (int index = 0; index < matrix.Length; index++) {
            result[index] = new bool[matrix[index].Length];
            matrix[index].CopyTo(result[index], 0);
        }
        return result;
    }
    private bool Next(int row, int col, bool[][] matrix) {
        bool now = matrix[row][col];
        int count = GetCell(matrix, row - 1, col - 1)
                + GetCell(matrix, row - 1, col)
                + GetCell(matrix, row - 1, col + 1)
                + GetCell(matrix, row, col - 1)
                + GetCell(matrix, row, col + 1)
                + GetCell(matrix, row + 1, col - 1)
                + GetCell(matrix, row + 1, col)
                + GetCell(matrix, row + 1, col + 1);
        if (now) {
            return (count == 2 || count == 3);
        } else {
            return (count == 3);
        }
    }
    private int GetCell(bool[][] matrix, int rowIndex, int colIndex) {
        int y = rowIndex;
        while (y < 0) y += matrix.Length;
        while (y >= matrix.Length) y -= matrix.Length;

        bool[] row = matrix[y];
        int x = colIndex;
        while (x < 0) x += row.Length;
        while (x >= row.Length) x -= row.Length;

        return row[x]? 1: 0;
    }


    [STAThread]
    static void Main(string[] args) {
        LifeGame game = new LifeGame(10, 10);

        Console.WriteLine("t={0}", game.Time);
        Console.WriteLine(game.GetDisplayMatrix());
        game.NextStep();
        Console.WriteLine("t={0}", game.Time);
        Console.WriteLine(game.GetDisplayMatrix());

        Console.ReadLine();
    }
}
LifeGame書いたことなかったから、間引きなしで。
グライダーが動いたので多分合ってる?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <conio.h>

#define WIDTH  10
#define HIGHT 10

void next_gen(int a[HIGHT][WIDTH]){
    int life;
    int x,y;
    int x_l,x_r,y_u,y_d;
    for(y=0;y<HIGHT;y++){
        y_u=(y+ 9)%HIGHT;
        y_d=(y+11)%HIGHT;
        for(x=0;x<WIDTH;x++){
            x_l=(x+ 9)%WIDTH;
            x_r=(x+11)%WIDTH;
            
            life= (a[y_u][x_l]&1)+(a[y_u][x]&1)+(a[y_u][x_r]&1)
                 +(a[ y ][x_l]&1)              +(a[ y ][x_r]&1)
                 +(a[y_d][x_l]&1)+(a[y_d][x]&1)+(a[y_d][x_r]&1);

            if((life|(a[y][x]&1))==3) a[y][x]|=2;
        }
    }
    for(y=0;y<HIGHT;y++){
        for(x=0;x<WIDTH;x++){
            a[x][y]>>=1;
        }
    }
}

void put_gen(int a[HIGHT][WIDTH]){
    int x,y;
    for(y=0;y<HIGHT;y++){
        for(x=0;x<WIDTH;x++){
            putchar('[');
            putchar(a[y][x]==1?'*':' ');
            putchar(']');
        }
            putchar('\n');
    }
}

void lifegame(int a[HIGHT][WIDTH]){
    int gen=0;
    do{
        printf("T=%d\n",gen);
        put_gen(a);
        next_gen(a);
        gen++;
    }while(getch()==0x20);
}

int main(){
    int a[HIGHT][WIDTH]={
/* 出題
        {0,1,0,0,0,0,1,1,1,0},
        {0,0,0,0,1,0,0,1,1,0},
        {0,0,0,1,0,0,1,0,1,0},
        {1,0,1,1,0,0,1,0,0,0},
        {0,1,0,0,0,0,0,0,1,0},
        {1,0,0,0,1,0,1,1,0,1},
        {0,1,0,0,0,0,1,0,0,0},
        {0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,1,0,0,1},
        {0,0,0,0,1,1,0,0,1,0}
/*/
//グライダー
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,1,0,0,0,0,0,0},
        {0,0,1,0,0,0,0,0,0,0},
        {0,0,1,1,1,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
//*/
    };
    lifegame(a);
    
    return 0;
}
題意を間違えたみたいなんで追加修正
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void init_life(int a[HEIGHT][WIDTH]){
    int x,y;
    int count=0;
    
    for(y=0;y<HEIGHT;y++){
        for(x=0;x<WIDTH;x++){
            a[y][x]=0;
        }
    }

    srand(time(NULL));
    do{
        x=rand()/(RAND_MAX/WIDTH);
        y=rand()/(RAND_MAX/HEIGHT);
        if(calc_life(a,x,y)<=(2+(rand()/(RAND_MAX/2)))){
            a[y][x]=1;
            count++;
        }
    }while(count<((HEIGHT*WIDTH)*(2+(rand()/(RAND_MAX/2)))/10));
}

int main(){
    int a[HEIGHT][WIDTH];
    init_life(a);
    lifegame(a);
    
    return 0;
}

ライフゲームとは関係ないところで妙な小細工

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
require 'curses'
require 'enumerator'

class Object
  def make_instance_variables (_binding)
    eval(<<'EOC', _binding)
      local_variables.each do
        |lv_name|
        instance_variable_set("@#{lv_name}", eval(lv_name))
      end
EOC
  end
end

class World
    attr_reader :height, :width, :rate

    def initialize (height, width, rate)
        make_instance_variables(binding)
        @cells = Array.new(height * width) { rand < rate }
    end

    def [] (x, y)
        @cells[fix_position(x, y)]
    end

    def []= (x, y, v)
        @cells[fix_position(x, y)] = v
    end

    def livings (x, y)
        result = 0
        (-1..1).each {|dy| (-1..1).each {|dx| result += 1 if self[x + dx, y + dy] unless dx == 0 and dy == 0 }}
        result
    end

    def update
        @cells = @cells.dup.enum_for(:each_with_index).map do
            |l, idx|
            x, y = idx % width, idx / width
            ls = livings(x, y)
            if l  
                (2..3) === ls
            else
                ls == 3
            end
        end
    end

    def inspect
        @cells.map {|it| "[#{it ? '*' : ' '}]" }.join.gsub(/.{#{3*width}}/){|it| "#{it}\n" }
    end

    private

    def fix_position (x, y)
        y % width * width + x % height
    end
end

class OptionParser
    def self.parse (args)
        require 'ostruct'
        require 'optparse'

        options = OpenStruct.new
        options.population = 0.3
        options.interval = 0.5
        options.height = options.width = 10

        parser = OptionParser.new do
            |parser|
            parser.banner = "Usage: #{File.basename($0)} [options] "
            parser.on('-p', '--population-rate [RATE]') { |it| options.population = it.to_f }
            parser.on('-i', '--interval [SEC]') { |it| options.interval = it.to_f }
            parser.on('-w', '--width [WIDTH]') { |it| options.interval = it.to_f }
            parser.on('-h', '--height [HEIGHT]') { |it| options.interval = it.to_f }
        end

        parser.parse!(args)
        options
    rescue
        puts parser.help
        exit
    end
end

options = OptionParser.parse(ARGV)

w = World.new(options.width, options.height, options.population) 

Curses.init_screen
loop do
    Curses.clear
    Curses.addstr(w.inspect)
    Curses.refresh
    sleep(options.interval)
    w.update
end
Curses.close_screen
ぴこぴこ動くので、多分間違ってないかと(^ ^;
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
!変数宣言が必要
/*初期マップとは配列=,
"0,1,0,0,0,0,1,1,1,0
0,0,0,0,1,0,0,1,1,0
0,0,0,1,0,0,1,0,1,0
1,0,1,1,0,0,1,0,0,0
0,1,0,0,0,0,0,0,1,0
1,0,0,0,1,0,1,1,0,1
0,1,0,0,0,0,1,0,0,0
0,0,0,0,0,0,0,0,0,1
1,0,0,0,0,0,1,0,0,1
0,0,0,0,1,1,0,0,1,0"
wとは整数=9
hとは整数=9*/

初期マップとは配列=,
"0,0,0,0,0,0
0,0,0,1,1,0
0,0,0,1,1,0
0,1,1,0,0,0
0,1,1,0,0,0
0,0,0,0,0,0"

wとは整数=5
hとは整数=5
現マップとは配列=初期マップ
次マップとは配列
iとは整数
jとは整数
セル数とは整数
マップラベルとはラベル

マップラベル=現マップをマップ整形
1の間
    iで0からhまで繰り返す
        jで0からwまで繰り返す
            セル数=周囲セル数取得(現マップ,i,j,h,w)
            もし(現マップ[i,j]=0)ならば
                もし(セル数=3)ならば
                    次マップ[i,j]=1 #誕生
                違えば
                    次マップ[i,j]=0 #死亡
            違えば
                もし(セル数=2||セル数=3)ならば
                    次マップ[i,j]=1 #維持
                違えば
                    次マップ[i,j]=0 #死亡
    現マップ=次マップ
    マップラベル=現マップをマップ整形
    0.2秒待つ

●マップ整形(mapを)
    tmpとは文字列
    tmplineとは文字列
    mapを反復
        tmpline=対象の改行を""に置換
        tmpline=tmplineの0を" "に置換
        tmpline=tmplineの1を"■"に置換
        tmp=tmp&tmpline&改行
    tmpで戻る

●周囲セル数取得(map,y,x,h,w)
    nxとは整数
    nyとは整数
    countとは整数
    "{y-1},{x-1}
{y-1},{x}
{y-1},{x+1}
{y},{x-1}
{y},{x+1}
{y+1},{x-1}
{y+1},{x}
{y+1},{x+1}"を反復
        もし(対象[0,0]=-1)ならば
            ny=h
        違えば
            ny=対象[0,0]
        もし(対象[0,1]=-1)ならば
            nx=w
        違えば
            nx=対象[0,1]
        もし(map[ny,nx]=1)ならば
            count=count+1
    countで戻る
失敗しました。
全部貼らなきゃだった・・・

題意を取り違えてたっぽいので追加修正。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

#define WIDTH  10
#define HEIGHT 10


int calc_life(int a[HEIGHT][WIDTH],int x,int y){
    int life;
    int x_l,x_r,y_u,y_d;
    y_u=(y+HEIGHT-1)%HEIGHT;
    y_d=(y+1)%HEIGHT;
    x_l=(x+WIDTH-1)%WIDTH;
    x_r=(x+1)%WIDTH;
            
    life= (a[y_u][x_l]&1)+(a[y_u][x]&1)+(a[y_u][x_r]&1)
         +(a[ y ][x_l]&1)              +(a[ y ][x_r]&1)
         +(a[y_d][x_l]&1)+(a[y_d][x]&1)+(a[y_d][x_r]&1);
    return life;
}
void next_gen(int a[HEIGHT][WIDTH]){
    int life;
    int x,y;
    for(y=0;y<HEIGHT;y++){
        for(x=0;x<WIDTH;x++){
            life=calc_life(a,x,y);

            if((life|(a[y][x]&1))==3) a[y][x]|=2;
        }
    }
    for(y=0;y<HEIGHT;y++){
        for(x=0;x<WIDTH;x++){
            a[x][y]>>=1;
        }
    }
}

void put_gen(int a[HEIGHT][WIDTH]){
    int x,y;
    for(y=0;y<HEIGHT;y++){
        for(x=0;x<WIDTH;x++){
            putchar('[');
            putchar(a[y][x]==1?'*':' ');
            putchar(']');
        }
            putchar('\n');
    }
}

void lifegame(int a[HEIGHT][WIDTH]){
    int gen=0;
    do{
        printf("T=%d\n",gen);
        put_gen(a);
        next_gen(a);
        gen++;
    }while(getch()==0x20);
}

void init_life(int a[HEIGHT][WIDTH]){
    int x,y;
    int count=0;
    
    for(y=0;y<HEIGHT;y++){
        for(x=0;x<WIDTH;x++){
            a[y][x]=0;
        }
    }

    srand(time(NULL));
    do{
        x=rand()/(RAND_MAX/WIDTH);
        y=rand()/(RAND_MAX/HEIGHT);
        if(calc_life(a,x,y)<=(2+(rand()/(RAND_MAX/2)))){
            a[y][x]=1;
            count++;
        }
    }while(count<((HEIGHT*WIDTH)*(2+(rand()/(RAND_MAX/2)))/10));
}

int main(){
    int a[HEIGHT][WIDTH];
    init_life(a);
    lifegame(a);
    
    return 0;
}
グダグダしてきましたが、Wikipediaによると"23/3"などというルール表記があるようなのでそれに対応。
世代スキップも追加。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

#define WIDTH  10
#define HEIGHT 10

/* セルの生死判定 */
int calc_life(int a[HEIGHT][WIDTH],int x,int y){
    int life;
    int x_l,x_r,y_u,y_d;
    y_u=(y+HEIGHT-1)%HEIGHT;
    y_d=(y+1)%HEIGHT;
    x_l=(x+WIDTH-1)%WIDTH;
    x_r=(x+1)%WIDTH;
            
    life= (a[y_u][x_l]&1)+(a[y_u][x]&1)+(a[y_u][x_r]&1)
         +(a[ y ][x_l]&1) /*注目セル */+(a[ y ][x_r]&1)
         +(a[y_d][x_l]&1)+(a[y_d][x]&1)+(a[y_d][x_r]&1);
    return life;
}

/* 世代の進行 */
void next_gen(int a[HEIGHT][WIDTH],char* rule){
    int life;
    int x,y;
    char* birth;
    char* ptr_rule;

    /* 誕生ルール検出 */
    birth=rule;
    while(*birth++!='/');
    
    /*生存・誕生判定*/
    for(y=0;y<HEIGHT;y++){
        for(x=0;x<WIDTH;x++){
            life=calc_life(a,x,y);
            
            if(a[y][x]&1){
                /*生存判定*/
                ptr_rule=rule;
                do{
                    if(life==*ptr_rule-'0') a[y][x]|=2;
                }while(*++ptr_rule!='/');
            }else{
                /*誕生判定*/
                ptr_rule=birth;
                do{
                    if(life==*ptr_rule-'0') a[y][x]|=2;
                }while(*++ptr_rule);
            }
        }
    }
    
    /* 次世代へ進行 */
    for(y=0;y<HEIGHT;y++){
        for(x=0;x<WIDTH;x++){
            a[x][y]>>=1;
        }
    }
}

/* 現世代の表示 */
void put_gen(int a[HEIGHT][WIDTH]){
    int x,y;
    for(y=0;y<HEIGHT;y++){
        for(x=0;x<WIDTH;x++){
            printf("[%c]",a[y][x]==1?'*':' ');
        }
        putchar('\n');
    }
}

/* ライフゲーム制御 */
void lifegame(int a[HEIGHT][WIDTH],char* rule){
    int gen=0;
    char c;
    int step;
    
    while(1){
        printf("T=%d\n",gen);
        put_gen(a);
        step=0;

        while(1){
            c=getche();
            if(c<'0'||'9'<c) break;
            step*=10;
            step+=c-'0';
        }
        if(c==0x1b) break;
        if(step==0&&(c==0x20||c==0x0d)) step=1;
        putchar('\n');
        while(step--){
            next_gen(a,rule);
            gen++;
        }
    }
}

/* ランダム初期値の設定 */
void init_life(int a[HEIGHT][WIDTH]){
    int x,y;
    int count=0;
    
    for(y=0;y<HEIGHT;y++){
        for(x=0;x<WIDTH;x++){
            a[y][x]=0;
        }
    }

    srand(time(NULL));
    do{
        x=rand()/(RAND_MAX/WIDTH);
        y=rand()/(RAND_MAX/HEIGHT);
        if(calc_life(a,x,y)<=(2+(rand()/(RAND_MAX/2)))){
            a[y][x]=1;
            count++;
        }
    }while(count<((HEIGHT*WIDTH)*(2+(rand()/(RAND_MAX/2)))/10));
}

int main(){
    int a[HEIGHT][WIDTH]={
/* 出題
        {0,1,0,0,0,0,1,1,1,0},
        {0,0,0,0,1,0,0,1,1,0},
        {0,0,0,1,0,0,1,0,1,0},
        {1,0,1,1,0,0,1,0,0,0},
        {0,1,0,0,0,0,0,0,1,0},
        {1,0,0,0,1,0,1,1,0,1},
        {0,1,0,0,0,0,1,0,0,0},
        {0,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,1,0,0,1},
        {0,0,0,0,1,1,0,0,1,0}
/*/
//グライダー
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,1,0,0,0,0,0,0},
        {0,0,1,0,0,0,0,0,0,0},
        {0,0,1,1,1,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
/*/
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,1,0,0,0,0,0,0},
        {0,0,1,1,0,1,0,0,0,0},
        {0,0,0,1,0,1,0,0,0,0},
        {0,0,0,0,0,1,0,0,0,0},
        {0,0,0,0,0,0,1,0,0,0},
        {0,0,0,0,0,0,1,0,1,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
//*/
    };
//    init_life(a);
    lifegame(a,"23/3");
//    lifegame(a,"23/36"); //HighLife?
    
    return 0;
}

すいません、配列が範囲を超える場合の処理を書いてませんでしたorz

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
●周囲セル数取得(map,y,x,h,w)
    nxとは整数
    nyとは整数
    countとは整数
    "{y-1},{x-1}
{y-1},{x}
{y-1},{x+1}
{y},{x-1}
{y},{x+1}
{y+1},{x-1}
{y+1},{x}
{y+1},{x+1}"を反復
        もし(対象[0,0]=-1)ならば,ny=h
        違えば,もし(対象[0,0]=h+1)ならば,ny=0
        違えば,ny=対象[0,0]
        もし(対象[0,1]=-1)ならば,nx=w
        違えば,もし(対象[0,1]=w+1)ならば,nx=0
        違えば,nx=対象[0,1]
        もし(map[ny,nx]=1)ならば
            count=count+1
    countで戻る

Swingで。特に工夫はなし。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.awt.*;
import java.util.Random;
import java.util.concurrent.*;
import javax.swing.*;

public class Life extends JFrame {
    private boolean[] cells;
    private final int pitch, w, h;

    public static void main(String[] args) {
        Life f = new Life(20, 20, 0.3);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public Life(final int w, final int h, final double rate) {
        super("Life");
        
        this.w = w;
        this.h = h;
        
        pitch = 5;
        cells = new boolean[h*w];
        
        initialize(rate);
        
        getContentPane().add(new JLabel(new Icon() {
            public int getIconHeight() { return h * pitch + pitch; }
            public int getIconWidth() { return w * pitch + pitch; }
            public void paintIcon(Component c, Graphics g, int x, int y) {
                g.setColor(Color.BLUE);
                for (int i = 0; i < h; i++) 
                    for (int j = 0; j < w; j++) 
                        if(cells[at(i, j)]) g.fillRect(j*pitch, i*pitch, pitch, pitch);
            }
        }));
        
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
            public void run() {
                update();
                repaint();
            }
        }, 1000L, 200L, TimeUnit.MILLISECONDS);
    }
    
    private void initialize(double rate) {
        final Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < h; i++) 
            for (int j = 0; j < w; j++) 
                cells[at(i, j)] = random.nextDouble() < rate;
                                              
    }
    private int at(int i, int j) {
        return i*w + j;
    }
    
    protected void update() {
        boolean[] newG = cells.clone();
        for (int i = 0; i < h; i++) 
            for (int j = 0; j < w; j++) 
                newG[at(i,j)] = next(i, j);
        cells = newG;
    }

    private boolean next(int i, int j) {
        final int u = (i+h-1)%h, d = (i+1)%h, l = (j+w-1)%w, r = (j+1)%w;
        int count = 0;
        if(cells[at(u, j)]) count++;
        if(cells[at(u, r)]) count++;
        if(cells[at(i, r)]) count++;
        if(cells[at(d, r)]) count++;
        if(cells[at(d, j)]) count++;
        if(cells[at(d, l)]) count++;
        if(cells[at(i, l)]) count++;
        if(cells[at(u, l)]) count++;
        
        return ((cells[at(i, j)] && (count == 2 || count == 3))  ||
                (!cells[at(i, j)] && count == 3));
    }
}
そのままだとつまらないので、再帰で書いてみました。

実行結果(3世代抜粋)
------------------------------------
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□■□□□
□□□□□■□□□□
□□□□□■■■□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□

□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□■□■□□
□□□□□■■□□□
□□□□□□■□□□
□□□□□□□□□□
□□□□□□□□□□

□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□■□□□□
□□□□□■□■□□
□□□□□■■□□□
□□□□□□□□□□
□□□□□□□□□□
------------------------------------
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
public class LifeGame {
    private static class World {
        private static class Cell {
            private final Cell[] mAdjoiningCells = new Cell[8];
            private int mGeneration = 0;
            private boolean mIsOddLive = false;
            private boolean mIsEvenLive = false;

            public boolean next(int aGeneration) {
                boolean tIsLive = (aGeneration & 1) == 0 ? mIsEvenLive : mIsOddLive;

                if (aGeneration == mGeneration) {
                    return tIsLive;
                }

                mGeneration++;
                int tLiveCells = 0;
                for (int i = 0; i < 8; i++) {
                    tLiveCells += mAdjoiningCells[i].next(aGeneration) ? 1 : 0;
                }

                boolean tNext = tLiveCells == 3 ? true : tLiveCells == 2 ? tIsLive : false;
                if ((aGeneration & 1) == 0) {
                    mIsOddLive = tNext;
                } else {
                    mIsEvenLive = tNext;
                }
                return tIsLive;
            }
        }

        private final Cell[][] mMap;
        private final int mWidth;
        private final int mHeight;
        private int mGeneration;

        public World(boolean[][] aInitialValues) {
            int tHeight = aInitialValues.length;
            int tWidth = aInitialValues[0].length;
            mMap = new Cell[tWidth][tHeight];
            mWidth = tWidth;
            mHeight = tHeight;
            mGeneration = 0;
            createCell(0, 0);
            for (int x = 0; x < tWidth; x++) {
                for (int y = 0; y < tHeight; y++) {
                    mMap[x][y].mIsOddLive = aInitialValues[y][x];
                }
            }
        }

        private Cell createCell(int aX, int aY) {
            aX = (aX < 0 ? aX + mWidth : aX) % mWidth;
            aY = (aY < 0 ? aY + mHeight : aY) % mHeight;

            if (mMap[aX][aY] != null) {
                return mMap[aX][aY];
            }

            Cell tCell = new Cell();
            mMap[aX][aY] = tCell;
            tCell.mAdjoiningCells[0] = createCell(aX - 1, aY - 1);
            tCell.mAdjoiningCells[1] = createCell(aX + 0, aY - 1);
            tCell.mAdjoiningCells[2] = createCell(aX + 1, aY - 1);
            tCell.mAdjoiningCells[3] = createCell(aX + 1, aY + 0);
            tCell.mAdjoiningCells[4] = createCell(aX + 1, aY + 1);
            tCell.mAdjoiningCells[5] = createCell(aX + 0, aY + 1);
            tCell.mAdjoiningCells[6] = createCell(aX - 1, aY + 1);
            tCell.mAdjoiningCells[7] = createCell(aX - 1, aY + 0);
            return tCell;
        }

        public void next() {
            mMap[0][0].next(++mGeneration);
        }

        @Override
        public String toString() {
            final boolean tIsEven = (mGeneration & 1) == 0;
            StringBuilder tBuilder = new StringBuilder(mHeight * (mWidth + 1));
            for (int y = 0; y < mHeight; y++) {
                for (int x = 0; x < mWidth; x++) {
                    tBuilder.append((tIsEven ? mMap[x][y].mIsEvenLive : mMap[x][y].mIsOddLive) ? '■' : '□');
                }
                tBuilder.append('\n');
            }
            return new String(tBuilder);
        }
    }

    public static void main(String[] args) {
        boolean o = true;
        boolean _ = false;
        World tWorld = new World(new boolean[][] { // とりあえずグライダー
                {_,_,_,_,_,_,_,_,_,_},
                {_,_,_,_,_,_,_,_,_,_},
                {_,_,_,_,_,_,_,_,_,_},
                {_,_,_,_,_,_,_,_,_,_},
                {_,_,_,_,_,_,o,_,_,_},
                {_,_,_,_,_,o,_,_,_,_},
                {_,_,_,_,_,o,o,o,_,_},
                {_,_,_,_,_,_,_,_,_,_},
                {_,_,_,_,_,_,_,_,_,_},
                {_,_,_,_,_,_,_,_,_,_},
        });

        for (int i = 0; i < 100; i++) { // 100世代実行
            tWorld.next();
            System.out.println(tWorld);
        }
    }
}
  • (life-game board upper-time)で実行
    • boardは100要素の0, 1のリストとする
  • e以外を入力すると1ステップ進みステップ数と盤面を出力
  • eを入力すると打ち切り
  • ステップ数がupper-timeに到達したら終了

ところでt=1で(x,y)=(10,9)のセルは生きてるんじゃないでしょうか?

t=0で隣接する(10,8), (9, 10), (1,9)が生きているので.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
(use util.list)
(use srfi-1)

(define (life-next-board board) ;盤面の更新
  (define (life-neighbours n) ;隣接セルのインデックス
    (define (ln-in x y)
      (+ (* (modulo x 10) 10) (modulo y 10)))
    (receive
     (x y)
     (quotient&remainder n 10)
     (list (ln-in (- x 1) (- y 1))
           (ln-in (- x 1) y)
           (ln-in (- x 1) (+ y 1))
           (ln-in x (- y 1))
           (ln-in x (+ y 1))
           (ln-in (+ x 1) (- y 1))
           (ln-in (+ x 1) y)
           (ln-in (+ x 1) (+ y 1)))))
  (define (life-live? n board) ;セルが生きているかどうか
    (= (list-ref board n) 1))
  (define (life-next-cell n board) ;セルの更新
    (let [(count
           (apply +
                  (map (lambda (x) (list-ref board x))
                       (life-neighbours n))))]
      (cond [(life-live? n board)
            (if (or (= count 2) (= count 3)) 1 0)]
            [else
            (if (= count 3) 1 0)])))
  (map (lambda (n) (life-next-cell n board))
       (iota 100)))

(define (life-print b t) ;出力用
  (begin
    (newline)
    (format #t "Time = ~d" t)
    (newline)
    (map print (slices b 10))))

(define (life-game b u-t) ;本体
  (define (lg-in b t)
    (let ((c (read-char)))
      (if (not (char=? #\e c))
          (unless (> t u-t)
            (begin
              (life-print b t)
              (lg-in (life-next-board b) (+ t 1)))))))
  (lg-in b 0))

(define b1 (list
            0 1 0 0 0 0 1 1 1 0
            0 0 0 0 1 0 0 1 1 0
            0 0 0 1 0 0 1 0 1 0
            1 0 1 1 0 0 1 0 0 0
            0 1 0 0 0 0 0 0 1 0
            1 0 0 0 1 0 1 1 0 1
            0 1 0 0 0 0 1 0 0 0
            0 0 0 0 0 0 0 0 0 1
            1 0 0 0 0 0 1 0 0 1
            0 0 0 0 1 1 0 0 1 0))

(life-game b1 10)

確かにt=1で(x,y)=(10,9)のセルは生き残ってないとおかしいですね. (^ ^); すいません, こちらのコーディングにバグがありました.

枠のセルの判定を簡単にするためにwidth+2, height+2の配列を用意して一番外側に0を入れています.
無限ループにしてますが#    if t > 20:returnの部分を変更してやれば任意のステップで停止します.
グライダーの実行結果
t=0
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [*] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [*] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [*] [*] [*] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
t=1
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [*] [ ] [*] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [*] [*] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [*] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
t=2
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [*] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [*] [ ] [*] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [*] [*] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#! -*- coding: utf-8 -*-
from random import random
width=10
height=10
def main(L1,L2,t):
    print 't=%d'%t
    for y in range(1,height+1):
        for x in range(1,width+1):
            s='[%s]'
            if L1[y][x]==1:
                s=s%'*'
            else:
                s=s%' '
            print s,
        print
    for y in range(1,height+1):
        for x in range(1,width+1):
            cnt=0
            for i in range(-1,2):
                for j in range(-1,2):
                    if i==0 and j==0:continue
                    if L1[y+i][x+j]==1:cnt+=1
            if L1[y][x]==0 and cnt==3:L2[y][x]=1
            elif L1[y][x]==1 and 2 <= cnt <=3: L2[y][x]=1
            else: L2[y][x]=0
#    if t > 20:return
    main(L2,L1,t+1)

if __name__=='__main__':
    L1=[[0 for i in range(width+2)] for j in range(height+2)]
    for i in range(1,height+1):
        for j in range(1,width+1):
            if random()<=0.3:
                L1[i][j]=1
    L2=[[0 for i in range(width+2)] for j in range(height+2)]
#    確認用 グライダー
#     L1=[[0,0,0,0,0,0,0,0,0,0,0,0],
#         [0,0,0,0,0,0,0,0,0,0,0,0],
#         [0,0,0,0,0,0,0,0,0,0,0,0],
#         [0,0,0,0,0,0,0,0,0,0,0,0],
#         [0,0,0,0,0,0,0,0,0,0,0,0],
#         [0,0,0,0,1,0,0,0,0,0,0,0],
#         [0,0,0,1,0,0,0,0,0,0,0,0],
#         [0,0,0,1,1,1,0,0,0,0,0,0],
#         [0,0,0,0,0,0,0,0,0,0,0,0],
#         [0,0,0,0,0,0,0,0,0,0,0,0],
#         [0,0,0,0,0,0,0,0,0,0,0,0],
#         [0,0,0,0,0,0,0,0,0,0,0,0]]
    main(L1,L2,0)
こんなんでどうでしょう?
位置ごとに生死の情報を持たせるのではなく、
各セルに注目して、各セルに位置と生死の情報を持たせたらどんなコードになるかな?と思い書いてみました。
でも、周囲のセルをカウントするときに位置からセルの生死を判断してるので中途半端ですね。
間引きは題意がよくわからなかったので実装せず。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
//http://ja.doukaku.org/126/ 投稿用

//Wikipediaライフゲーム
//http://ja.wikipedia.org/wiki/%E3%83%A9%E3%82%A4%E3%83%95%E3%82%B2%E3%83%BC%E3%83%A0

using System;
using System.Collections.Generic;
class LifeGame {
    const int SIZE = 10;//変更したらCellクラスのSIZEも要変更
    static void Main(string[] args) {
        string start =
@"
□■□□□□■□□□
■□□□□■□□□□
■■■□□■■■□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□";//SIZE * SIZEの文字列
        start = start.TrimStart(new char[] { '\n', '\r' });//最初の改行を取り除く
        char[][] field = new char[SIZE][];//ライフゲームテーブル
        List<Cell> cells = new List<Cell>();//セル

        //startをfieldにセットする
        for(int y = 0; y < SIZE; y++) {//行でループ
            field[y] = start.Split(new char[] { '\n' })[y].ToCharArray();//改行で分割して文字配列にしてセット
        }

        //fieldからCellを生成
        for(int y = 0; y < SIZE; y++) {//field縦ループ
            for(int x = 0; x < SIZE; x++) {//field横ループ
                cells.Add(new Cell(field, x, y, field[y][x] == '■'));//Cellに座標をセットしてcellsに追加
            }
        }

        //メインループ
        while(true) {
            //出力
            Console.Clear();
            foreach(char[] str in field) {
                Console.WriteLine(str);
            }

            System.Threading.Thread.Sleep(300);//ウェイト            

            //次回の生死を判定、セット
            foreach(Cell cell in cells) {
                cell.SetNextLife();
            }

            //判定した生死をfieldに反映
            foreach(Cell cell in cells) {
                cell.SetField();
            }
        }
    }
}

//各セルのデータ
class Cell {
    const int SIZE = 10;//変更したらLifeGameクラスのSIZEも要変更
    char[][] Field;

    //位置
    int X;
    int Y;

    bool Life;//状態
    bool NextLife;//次回の状態(一時保存用)

    public Cell(char[][] field, int x, int y, bool life) {
        Field = field;
        X = x;
        Y = y;
        Life = life;
    }

    //次回の生死を判定
    public void SetNextLife() {
        switch(GetCount()) {
        case 3://誕生、維持
            NextLife = true;
            break;
        case 2://維持
            NextLife = Life;
            break;
        default://死亡
            NextLife = false;
            break;
        }
    }

    //判定した生死をfieldに反映
    public void SetField() {
        Field[Y][X] = NextLife ? '■' : '□';
        Life = NextLife;
    }

    //セル周囲の生きているセルをカウント
    private int GetCount() {
        int count = 0;
        for(int y_ = -1; y_ <= 1; y_++) {
            for(int x_ = -1; x_ <= 1; x_++) {
                if(!(x_ == 0 && y_ == 0)) {
                    int locationX = GetRoopLocation(X, x_);
                    int locationY = GetRoopLocation(Y, y_);
                    if(Field[locationY][locationX] == '■') count++;
                }
            }
        }
        return count;
    }

    //fieldの端と端を繋ぐ
    private int GetRoopLocation(int location, int direction) {
        switch(location + direction) {
        case -1:
            return SIZE - 1;
        case SIZE:
            return 0;
        default:
            return location + direction;
        }
    }
}
がっつりと勘違いしてました。
こっそりと修正。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
//http://ja.doukaku.org/126/ 投稿用

//Wikipediaライフゲーム
//http://ja.wikipedia.org/wiki/%E3%83%A9%E3%82%A4%E3%83%95%E3%82%B2%E3%83%BC%E3%83%A0

using System;
using System.Collections.Generic;
class LifeGame {
    const int SIZE = 10;//変更したらCellクラスのSIZEも要変更
    static void Main(string[] args) {
        string start =
@"
□■□□□□■□□□
■□□□□■□□□□
■■■□□■■■□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□";//SIZE * SIZEの文字列
        start = start.TrimStart(new char[] { '\n', '\r' });//最初の改行を取り除く
        char[][] field = new char[SIZE][];//ライフゲームテーブル
        List<Cell> cells = new List<Cell>();//セル

        //startをfieldにセットする
        //for(int y = 0; y < SIZE; y++) {//行でループ
        //    field[y] = start.Split(new char[] { '\n' })[y].ToCharArray();//改行で分割して文字配列にしてセット
        //}

        //ランダムにfieldを生成
        Random rnd = new Random();
        for(int j = 0 ;j<SIZE;j++) {
            field[j] = new char[SIZE];
            for(int i = 0; i < SIZE;i++ ) {
                field[j][i] = rnd.Next(0, 100) <= 30 ? '■' : '□';
            }
        }

        //fieldからCellを生成
        for(int y = 0; y < SIZE; y++) {//field縦ループ
            for(int x = 0; x < SIZE; x++) {//field横ループ
                cells.Add(new Cell(field, x, y, field[y][x] == '■'));//Cellに座標をセットしてcellsに追加
            }
        }

        //メインループ
        while(true) {
            //出力
            Console.Clear();
            foreach(char[] str in field) {
                Console.WriteLine(str);
            }

            System.Threading.Thread.Sleep(300);//ウェイト            

            //次回の生死を判定、セット
            foreach(Cell cell in cells) {
                cell.SetNextLife();
            }

            //判定した生死をfieldに反映
            foreach(Cell cell in cells) {
                cell.SetField();
            }
        }
    }
}

//各セルのデータ
class Cell {
    const int SIZE = 10;//変更したらLifeGameクラスのSIZEも要変更
    char[][] Field;

    //位置
    int X;
    int Y;

    bool Life;//状態
    bool NextLife;//次回の状態(一時保存用)

    public Cell(char[][] field, int x, int y, bool life) {
        Field = field;
        X = x;
        Y = y;
        Life = life;
    }

    //次回の生死を判定
    public void SetNextLife() {
        switch(GetCount()) {
        case 3://誕生、維持
            NextLife = true;
            break;
        case 2://維持
            NextLife = Life;
            break;
        default://死亡
            NextLife = false;
            break;
        }
    }

    //判定した生死をfieldに反映
    public void SetField() {
        Field[Y][X] = NextLife ? '■' : '□';
        Life = NextLife;
    }

    //セル周囲の生きているセルをカウント
    private int GetCount() {
        int count = 0;
        for(int y_ = -1; y_ <= 1; y_++) {
            for(int x_ = -1; x_ <= 1; x_++) {
                if(!(x_ == 0 && y_ == 0)) {
                    int locationX = GetRoopLocation(X, x_);
                    int locationY = GetRoopLocation(Y, y_);
                    if(Field[locationY][locationX] == '■') count++;
                }
            }
        }
        return count;
    }

    //fieldの端と端を繋ぐ
    private int GetRoopLocation(int location, int direction) {
        switch(location + direction) {
        case -1:
            return SIZE - 1;
        case SIZE:
            return 0;
        default:
            return location + direction;
        }
    }
}

Common Lisp です。あえて CLOS(Common Lisp Object System)で。

print-object で印字形式を設定していること、setf で更新している位であとは普通です。

こんな感じで試します。

cl-user(27): (setq b (make-glider))

#<board

.X........

X.........

XXX.......

..........

..........

..........

..........

..........

..........

..........

>

cl-user(28): (update b)

#<board

..........

X.X.......

XX........

.X........

..........

..........

..........

..........

..........

..........

>

初めてライフゲームを実装して、とても楽しかったです。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
;;;
;; dokaku 126
;;

(defclass board ()
  ((width :accessor board-width :initarg :w)
   (height :accessor board-height :initarg :h)
   (cells :accessor board-cells :initarg :cells)))

(defmethod print-object ((board board) stream)
  (print-unreadable-object (board stream)
    (format stream "board~%")
    (loop for y from 0 below (board-height board)
    do
      (loop for x from 0 below (board-width board)
          do
        (format stream "~a" (if (cell board x y) "X" ".")))
      (format stream "~%"))))

(defun make-board (w h)
  "constructor"
  (make-instance 'board :w w :h h :cells (make-array (list w h) :initial-element nil)))

(defun make-random-board (w h)
  (let ((board (make-board w h)))
    (loop for y from 0 below (board-height board)
    do
      (loop for x from 0 below (board-width board)
          do
        (setf (cell board x y) (< (random 10) 3))))
    board))

(defmethod cell ((board board) x y)
  "accessor"
  (aref (board-cells board) (mod x (board-width board)) (mod y (board-height board))))

;; (setf (cell board x y) value) 
(defsetf cell (board x y) (value)
  `(setf (aref (board-cells ,board) (mod ,x (board-width ,board))
           (mod ,y (board-height ,board))) ,value))

(defmethod cell-neighbours ((board board) x y)
  (list (cell board (1- x) (1- y))
    (cell board x (1- y))
    (cell board (1+ x) (1- y))
    (cell board (1- x) y)
    (cell board (1+ x) y)
    (cell board (1- x) (1+ y))
    (cell board x (1+ y))
    (cell board (1+ x) (1+ y))))

(defmethod cell-survivep ((board board) x y)
  (let ((c (cell board x y))
    (n (count-if #'identity (cell-neighbours board x y))))
    (cond
     ((and (not c) (= n 3)) t) ;; born
     ((and c (or (= n 3) (= n 2))) t) ;; keep
     (t nil)))) ;; die

(defmethod update ((board board))
  (let ((next
     (loop for y from 0 below (board-height board)
         append
           (loop for x from 0 below (board-width board)
           collect (list x y (cell-survivep board x y))))))
    (loop for elt in next
    do
      (destructuring-bind (x y v) elt
        (setf (cell board x y) v))))
  board)

(defun make-blinker ()
  (let ((b (make-board 10 10)))
    (setf (cell b 1 0) t
      (cell b 1 1) t
      (cell b 1 2) t)
    b))

(defun make-glider ()
  (let ((b (make-board 10 10)))
    (setf (cell b 1 0) t
      (cell b 0 1) t
      (cell b 0 2) t
      (cell b 1 2) t
      (cell b 2 2) t)
    b))

Squeak Smalltalk で、二次元配列オブジェクト(a Matrix)を使って書いてみました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| 行数 世代 現状 次面 八方 |

行数 := 10. 世代 := 50.
現状 := Matrix new: 行数 tabulate: [:行# :列# | #(1 0 0) atRandom].
次面 := Matrix new: 行数.
八方 := OrderedCollection new.
(-1 to: 1) asDigitsToPower: 2 do: [:組 | 八方 add: 組 first @ 組 second].
八方 remove: 0@0.

World findATranscript: nil.
世代 timesRepeat: [
    Transcript cr; show: (String streamContents: [:ss |
        (1 to: 行数) do: [:行# |
            (現状 atRow: 行#) do: [:idx | ss nextPut: ('□■' at: idx + 1)].
            ss cr]]).

    次面 atAllPut: 0.
    現状 indicesDo: [:行# :列# |
        | 総数 |
        総数 := 八方 inject: 0 into: [:和 :Δ |
            | 位置 |
            位置 := 行#@列# + Δ - 1 \\ 行数 + 1.
            和 + (現状 at: 位置 x at: 位置 y)].
        次面 at: 行# at: 列# put: (総数 caseOf: {
            [2] -> [現状 at: 行# at: 列#].
            [3] -> [1]} otherwise: [0])].

    現状 := 次面 flag: (次面 := 現状)]

Squeak Smalltalk の(Erlang にこそ及ばないものの…)比較的軽量なスレッドを利用して、全セルにおける生死の判断をマルチスレッドで処理してみました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| 行数 マス目 ワーカ再開用 メイン中断用 スレッド群 |
行数 := 10.
マス目 := Matrix new: 行数 tabulate: [:行# :列# | #value -> #(0 0 1) atRandom].
ワーカ再開用 := OrderedCollection new.
メイン中断用 := OrderedCollection new.
スレッド群 := OrderedCollection new.
マス目 withIndicesDo: [:セル :行# :列# |
    | 再開指示 完了伝達 隣接セル群  |
    再開指示 := ワーカ再開用 add: Semaphore new.
    完了伝達 := メイン中断用 add: Semaphore new.
    隣接セル群 := {0@1. 1@1. 1@0. 1@-1. 0@-1. -1@-1. -1@0. -1@1} collect: [:Δ |
        | 位置 |
        位置 := 行#@列# + Δ - 1 \\ 行数 + 1.
        マス目 at: 位置 x at: 位置 y].
    スレッド群 add: [[
        | 計 |
        再開指示 wait.
        計 := 隣接セル群 count: [:隣接セル | 隣接セル value > 0].
        計 = 2 ifTrue: [計 := 計 + セル value].
        完了伝達 signal.
        再開指示 wait.
        セル value: (計 = 3 ifTrue: [1] ifFalse: [0]).
        完了伝達 signal] repeat
    ] fixTemps fork].

World findATranscript: nil.
[50 timesRepeat: [
    Transcript cr; show: (String streamContents: [:ss |
        (1 to: 行数) do: [:行# | (マス目 atRow: 行#) do: [:セル |
            ss nextPut: ('■□' atWrap: セル value)].
            ss cr]]).

    ワーカ再開用 do: [:再開指示 | 再開指示 signal].
    メイン中断用 do: [:完了伝達 | 完了伝達 wait].
    ワーカ再開用 do: [:再開指示 | 再開指示 signal].
    メイン中断用 do: [:完了伝達 | 完了伝達 wait]].
] ensure: [スレッド群 do: [:スレッド | スレッド terminate]]
死ぬことが予想されるセルを殺して, 周囲のセルを活かました. 
生存率は2-3倍ほどに上昇. 
行を減らすために`and'を利用してやたら文を連結してますが, 
結合度については考慮しているので, セミコロンに置き替えて読んで下さっても
同じことです. 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require 'Matrix'
require 'kconv'
N, M = 10, 10
Density = 0.7
class CellMatrix
  Lived, Died = '[*]', '[ ]'
  Threshold = 4 and ModerateDensity = 0.5
  def initialize(n, m, &block)
    @cell_matrix = Array.new(n){|i| Array.new(m){|j| block_given? ? (yield [i, j]) : 0}}
    @time, @victim = 0, 0
  end
  def gen_seed(n)
    i, j = rand(r_size), rand(c_size)
    live(i,j) && n -= 1 if at(i,j) == 0
    gen_seed(n) if n > 0
  end
  def step
    env_mat = get_env and each{|i,j|
      case at(i,j)
      when 0: live(i,j) if env_mat.at(i,j) == 3
      when 1: die(i,j)  if env_mat.at(i,j) != 2..3
      end
    } and @time += 1
  end
  def thin_out #間引き
    env_mat = get_env and each{|i,j|
      max = {:pos => [], :value => 0} and env_mat.scan_env(i,j){|k,l|
        max[:pos] = [k,l] and max[:value] = env_mat.at(k,l) if env_mat.at(k,l) > max[:value]
      }
      kill(*max[:pos]) and @victim += 1 if max[:value] >= Threshold and at(*max[:pos]) == 1
    } and remain <= r_size * c_size * ModerateDensity ? true : thin_out
  end
  def dup; CellMatrix.new(r_size, c_size){|i,j| at(i,j)} end
  def remain; count = 0 and each{|i,j| count += at(i,j)} and count end
  def output(comment="")
    puts "t = #{@time} Remain: #{remain}, Victim: #{@victim} ##{comment}\n#{out}\n".tosjis
  end
  protected
  def at(i,j) @cell_matrix[i][j] end
  def each(&block) r_size.times{|i| c_size.times{|j| yield [i,j]}} end
  def scan_env(i, j, &block)
    a = [i == 0 ? r_size - 1 : i-1, i, i == r_size - 1 ? 0 : i+1]
    b = [j == 0 ? c_size - 1 : j-1, j, j == c_size - 1 ? 0 : j+1]
    a.each{|k| b.each{|l| yield [k,l] unless k == i && l == j}}
  end
  private
  def out; @cell_matrix.map{|line| "#{line.map{|x| x == 0 ? Died : Lived}.join}\n"}.join end
  def r_size;   @cell_matrix.size end
  def c_size;   @cell_matrix.first.size end
  def live(i,j) @cell_matrix[i][j] = 1 end
  def die(i,j)  @cell_matrix[i][j] = 0 end
  alias :kill :die
  def get_env #周囲のセルの状態
    CellMatrix.new(r_size, c_size){|i,j|
      count = 0 and scan_env(i,j){|k,l| count += at(k,l)} and count
    }
  end
end
real = CellMatrix.new(N, M)
initial = (N*M*Density).to_i
real.gen_seed(initial)
real.output('過密状態')
virtual = real.dup and virtual.step
virtual.output('間引きなし')
real.thin_out and real.step
real.output('間引きあり')

初投稿です 間引きに関しては・・・これでいいのかよくわかりません。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        LifeGame lg = new LifeGame(10, 10, 0.3, true);
        short i = 1;
        while (i != 0)
        {
            Console.Clear();
            Console.WriteLine("t = {0}", i++);
            lg.outputConsole();
            lg.scanField();

            System.Threading.Thread.Sleep(100);
        }
    }
}

class LifeGame
{
    public const int DEAD = 0;
    public const int ALIVE = 1;
    //横の長さ
    private int width_;
    public int Width{get{return width_;}}
    //縦の長さ
    private int height_;
    public int Height{get{return height_;}}
    //フィールド
    private int[,] field;
    //間引きのON(true)、OFF(false)
    private bool skipPixelFlag;

    public LifeGame(int w, int h, double rate, bool flag)
    {
        width_ = w;
        height_ = h;
        skipPixelFlag = flag;
        field = new int[w, h];
        createField(rate);
        //デバッグ用
        //width_ = 10;
        //height_ = 10;
        //field = new int[10, 10]
        //{
        //    {0,1,0,0,0,0,0,0,0,0},
        //    {0,0,1,0,0,0,0,0,0,0},
        //    {1,1,1,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0}
        //};
    }

    //ランダム生成
    private void createField(double rate)
    {
        int count = (int) (Width * Height * rate);
        Random random = new Random();
        do
        {
            int w = random.Next(Width), h = random.Next(Height);
            if (field[w, h] == DEAD) field[w, h] = ALIVE; else continue;
            count--;
        } while (count > 0);
    }

    //次の世代作成
    public void scanField()
    {
        int[,] temp = new int[Width, Height];
        for (int i = 0; i < Width; i++)
            for (int j = 0; j < Height; j++)
            {
                int value = aroundField(i, j);

                if (value == 3) temp[i, j] = ALIVE;
                else if (value == 2) temp[i, j] = field[i, j];
                else temp[i, j] = DEAD;
            }

        field = (int[,]) (temp.Clone());
        if (skipPixelFlag) skipPixelField();//間引き
    }

    //間引き
    //といっても、これでいいのか不明。
    //周りに4個以上ALIVEがあったらその枡をDEADにする
    private void skipPixelField()
    {
        for (int i = 0; i < Width; i++)
            for (int j = 0; j < Height; j++)
            {
                int value = aroundField(i, j);
                if (value > 4) field[i, j] = DEAD;
            }

    }

    //周りの生きてる枡の数
    private int aroundField(int w, int h)
    {
        int sum = 0;
        for (int i = w - 1; i <= w + 1; i++)
            for (int j = h - 1; j <= h + 1; j++)
                if (i != w || j != h)
                    sum += field[getIndex(i, Width), getIndex(j, Height)];
        return sum;
    }

    //ループインデックス作成
    private int getIndex(int n, int max)
    {
        return (n + max) % max;
    }

    //出力
    public void outputConsole()
    {
        for (int i = 0; i < Width; i++)
        {
            for (int j = 0; j < Height; j++)
            {
                Console.Write((field[i, j] == ALIVE) ? "■" : "□");
            }
            Console.WriteLine();
        }
        Console.WriteLine();
    }
}
普通に。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import std.string, std.conv, std.contracts,
       std.random, std.stdio, std.c.time;

class Field {
    private uint width_, height_;
    private bool[] data_;
    
    this(uint width, uint height) {
        this.width_ = width;
        this.height_ = height;
        this.data_ = new bool[width * height];
    }
    
    const uint width() { return this.width_; }
    const uint height() { return this.height_; }
    
    const bool opIndex(uint x, uint y)
        in {
            assert(x < this.width);
            assert(y < this.height);
        }
        body {
            return this.data_[this.width * y + x];
        }
        
    bool opIndexAssign(bool value, uint x, uint y)
        in {
            assert(x < this.width);
            assert(y < this.height);
        }
        body {
            return this.data_[this.width * y + x] = value;
        }
    
    const string toString() {
        const len = (3 * this.width) * this.height + newline.length * (this.height - 1);
        auto s = new char[len], idx = 0;
        foreach(y; 0 .. this.height) {
            foreach(x; 0 .. this.width) {
                s[idx .. idx + 3] = this[x, y] ? "[*]" : "[ ]";
                idx += 3;
            }
            if(idx != len) {
                s[idx .. idx + newline.length] = newline;
                idx += newline.length;
            }
        }
        return assumeUnique(s);
    }
    
    const Field nextGeneration() {
        const w = this.width, h = this.height;
        Field f = new Field(w, h);
        foreach(y; 0 .. h) {
            foreach(x; 0 .. w) {
                int c;
                int l = (x + w - 1) % w, r = (x + 1) % w,
                    u = (y + h - 1) % h, d = (y + 1) % h;
               
                if(this[l, u]) c++; if(this[x, u]) c++; if(this[r, u]) c++;
                if(this[l, y]) c++;                     if(this[r, y]) c++;
                if(this[l, d]) c++; if(this[x, d]) c++; if(this[r, d]) c++;
                
                if(c == 3 || this[x, y] && c == 2)
                    f[x, y] = true;
            }
        }
        return f;
    }
}

void main(string[] args) {
    if(args.length < 3) return;
    auto width = to!(uint)(args[1]), height = to!(uint)(args[2]);
    
    auto f = new Field(width, height);
    auto rgen = Random(unpredictableSeed);
    foreach(y; 0 .. height) {
        foreach(x; 0 .. width) {
            f[x, y] = uniform!(int)(rgen, 0, 10) < 3;
        }
    }
    uint gen = 0;
    while(true) {
        writeln("Generation ", ++gen);
        writeln(f);
        writeln("");
        f = f.nextGeneration;
        msleep(100);
    }
}
お題に対するコメントって良いんですよね。

大概のお題は、計算時間を計ることが多いのですが、
初期パターンを指定して、停止するまで(あるいは、
ループするまで)の時間を計ると、
実装の効率が比べられて良いかも知れませんね。
JavaScriptで書きました。

間引きは特に考慮していません。パターンはグライダーで、 0.5秒ごとに世代交代します。

Firefox 2.0.0.8, Internet Explorer 6, Opera 9.23で動作を確認。

  e.g.
    .*........
    ..*.......
    ***.......
    ..........
    ..........
    ..........
    ..........
    ..........
    ..........
    ..........
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink" xml:lang="ja" lang="ja">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Conway's game of life</title>
        <script type="text/javascript">
            $ = function (i) { return document.getElementById(i); }

            Function.prototype._setTimeout = 
            function (t, o, v) {
                var _ = this;
                return setTimeout(function () { _.apply(o, v); }, t);
            };

            var CellularAutomaton = 
            function (p, w, h) {
                this.p  = p;   // パターン
                this.w  = w;   // フィールドの横幅
                this.h  = h;   // フィールドの高さ
                this.c  = [];  // セル
                this._c = [];
                this.TI = 500; // 時間間隔
            };
            CellularAutomaton.prototype.generate = 
            function () {
                var i, j, n = 0, s = '', x, y;
                // フィールドを初期化
                for (y = 0; y < this.h; y++) {
                    for (x = 0; x < this.w; x++, n++) s += '<tt id="cell_' + n + '"></tt>';
                    s += '<br />';
                }
                document.body.innerHTML = s;
                this.clear();
                // パターンを描画
                for (i = 0; i < this.p.length; i++) {
                    for (j = 0; j < this.p[i].length; j++) {
                        if (this.p[i].charAt(j) == '.') continue;
                        n = this.h * i + j;
                        this.setCell(n, this.c[n] = 1);
                    }
                }
            };
            CellularAutomaton.prototype.clear = 
            function () {
                var n;
                for (n = this.w * this.h; n--; ) this.setCell(n, this.c[n] = 0);
            };
            CellularAutomaton.prototype.start = 
            function () {
                var n;
                // 次世代へ移行
                this.shift();
                for (n = 0; n < this.h * this.w; n++) this.c[n] = this._c[n];
                // 再帰
                this.start._setTimeout(this.TI, this, []);
            };
            CellularAutomaton.prototype.shift = 
            function () {
                var n = 0, x, y;

                for (y = 0; y < this.h; y++) {
                    for (x = 0; x < this.w; x++, n++) {
                        this._c[n] = this.judge(x, y, n);
                        if (this.c[n] != this._c[n]) this.setCell(n, this._c[n]);
                    }
                }
            };
            CellularAutomaton.prototype.judge = 
            function (x, y, n) {
                var i, j, l = 0, _x, _y;

                if ((x > 0 && x < this.w - 1) && (y > 0 && y < this.h - 1)) {
                    l = this.c[n - this.w - 1] + this.c[n - this.w] + this.c[n - this.w + 1]
                      + this.c[n          - 1]                      + this.c[n          + 1]
                      + this.c[n + this.w - 1] + this.c[n + this.w] + this.c[n + this.w + 1]
                      ;
                } else { // トーラス
                    for (i = -1; i < 2; i++) {
                        for (j = -1; j < 2; j++) {
                            if (i == 0 && j == 0) continue;

                            if (x + j == -1) _x = this.w - 1;
                            if (x + j == this.w) _x = 0;
                            if (x + j != -1 && x + j != this.w) _x = x + j;
                            if (y + i == -1) _y = this.h - 1;
                            if (y + i == this.h) _y = 0;
                            if (y + i != -1 && y + i != this.h) _y = y + i;

                            l += this.c[this.w * _y + _x];
                        }
                    }
                }

                if (this.c[n] == 0 && l == 3)             return 1; // 誕生
                if (this.c[n] == 1 && (l == 2 || l == 3)) return 1; // 維持
                return 0;                                           // 死亡
            };
            CellularAutomaton.prototype.setCell = 
            function (n, p) {
                $('cell_' + n).innerHTML = (p == 0) ? '.' : '*';
            };

            window.onload = 
            function () {
                var c = new CellularAutomaton([ '.*.' , '..*' , '***' ], 10, 10); c.generate(); c.start();
            };
        </script>
    </head>
    <body>
    </body>
</html>
大分色物な感じですが、超並列計算機 Connection Machine用のLisp処理系
である*LISP(スターリスプ)のCommon Lisp用のシミュレータパッケージを
使用して書いてみました。
本来、処理をプロセッサノードに割り振って並列に計算するので、今回位の計算
ならば、一度にどかんと計算させて、ループは全く使わないのが*LISPの流儀
だと思うのですが、構文がみつけられなかったため、全く普通に直列な
書き方になっており、あまり意味がないことになっています…。
表示は、グリッドの内容を綺麗に表示するプリティプリンタが付いてくるので、
それを使ってみました。
動作は、AllegroとCLISPで確認しています。
(SBCL等では、ソースを修正しないと*LISPがコンパイルできないようです。)
ソースは参考ページからダウンロード可能でチュートリアル付きです。

;; 実行結果 (グライダー)
     DIMENSION 0 (X)  ----->

0 1 0 0 0 0 0 0 0 0 
1 0 0 0 0 0 0 0 0 0 
1 1 1 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
(defpackage :doukaku-126 (:use :cl :*lisp))
(in-package :doukaku-126)
(*cold-boot :initial-dimensions '(10 10))

(defconstant +alive+ 1)
(defconstant +dead+ 0)

(defun grid10 (x y)
  (grid (mod x 10) (mod y 10)))

(defun get-env (grid x y)
  (values (pref grid (grid x y))
          (count +alive+
                 (list (pref grid (grid10 (1- x) (1- y)))
                       (pref grid (grid10 x (1- y)))
                       (pref grid (grid10 (1+ x) (1- y)))
                       (pref grid (grid10 (1- x) y))
                       (pref grid (grid10 (1+ x) y))
                       (pref grid (grid10 (1- x) (1+ y)))
                       (pref grid (grid10 x (1+ y)))
                       (pref grid (grid10 (1+ x) (1+ y)))))))

(defun gen-next (cur)
  (*let ((next +dead+))
    (loop :for x :from 0 :to 9 
          :do (loop :for y :from 0 :to 9 
                    :do (multiple-value-bind (self env) (get-env cur x y)
                          (cond ((and (eql +dead+ self) (= 3 env)) 
                                 (*setf (pref next (grid x y)) +alive+))
                                ((and (= +alive+ self) (<= 2 env 3))
                                 (*setf (pref next (grid x y)) +alive+))        
                                ('T (*setf (pref next (grid x y)) +dead+))))))
    next))

;; グライダーを作る
(defun make-glider ()
  (*let ((g +dead+))
    (*setf (pref g (grid 1 0)) +alive+
           (pref g (grid 0 1)) +alive+
           (pref g (grid 0 2)) +alive+
           (pref g (grid 1 2)) +alive+
           (pref g (grid 2 2)) +alive+)
    g))

;; 初期値をグライダーにしてループ 
(loop :for gen = (make-glider) then (gen-next gen)
      :do (ppp gen :mode :grid)
      :unless (y-or-n-p) :do (return))

Perlがなかったので投稿。C#のほぼそのままなので、あまりPerlらしいコードでない気がします。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/perl
use strict;
use warnings;

sub print_matrix($$) {
    my $turn = shift;
    my $matrix = shift;

    print "t={$turn}\n";
    foreach my $row(@$matrix) {
        foreach my $cell(@$row) {
            print '[', print_cell($cell), ']';
        }
        print "\n";
    }
    print "\n";
}
sub print_cell($) {
    return ($_[0]?'*':' ');
}

sub next_step($$) {
    my $turn = shift;
    my $matrix = shift;
    my $result = [];

    $turn++;
    for (my $y=0; $y<@$matrix; $y++) {
        push(@$result, []);
        for (my $x=0; $x<@{$matrix->[$y]}; $x++) {
            my $count = count_alive_cell($matrix, $y, $x);
            #print "($y,$x) = $count\n";
            push(@{$result->[-1]}, 
                ($count == 3)? 1:
                ($count == 2)? $matrix->[$y][$x]:
                0
            );
        }
    }
    return $turn, $result;
}
sub count_alive_cell($$$) {
    my $matrix = shift;
    my $y = shift;
    my $x = shift;
    return cell_value($matrix, $y-1, $x-1) + cell_value($matrix, $y-1, $x) + cell_value($matrix, $y-1, $x+1)
         + cell_value($matrix, $y  , $x-1) +                               + cell_value($matrix, $y  , $x+1)
         + cell_value($matrix, $y+1, $x-1) + cell_value($matrix, $y+1, $x) + cell_value($matrix, $y+1, $x+1)
}
sub cell_value($$$) {
    my $matrix = shift;
    my $y = shift;
    my $x = shift;
    $y -= @$matrix if ($y >= @$matrix);
    $x -= @{$matrix->[$y]} if ($x >= @{$matrix->[$y]});
    return $matrix->[$y][$x];
}


sub main($) {
    my $max_turn = shift;

    my $turn = 1;
#    my $matrix = [
#            [qw/0 1 0 0 0 0 1 1 1 0/],
#            [qw/0 0 0 0 1 0 0 1 1 0/],
#            [qw/0 0 0 1 0 0 1 0 1 0/],
#            [qw/1 0 1 1 0 0 1 0 0 0/],
#            [qw/0 1 0 0 0 0 0 0 1 0/],
#            [qw/1 0 0 0 1 0 1 1 0 1/],
#            [qw/0 1 0 0 0 0 1 0 0 0/],
#            [qw/0 0 0 0 0 0 0 0 0 1/],
#            [qw/1 0 0 0 0 0 1 0 0 1/],
#            [qw/0 0 0 0 1 1 0 0 1 0/],
#        ];
    my $matrix = [
            [qw/0 0 0 0 0 0 0 1 0 0/],
            [qw/0 0 0 0 0 0 1 0 0 0/],
            [qw/0 0 0 0 0 0 1 1 1 0/],
            [qw/0 0 0 0 0 0 0 0 0 0/],
            [qw/0 0 0 0 0 0 0 0 0 0/],
            [qw/0 0 0 0 0 0 0 0 0 0/],
            [qw/0 0 0 0 0 0 0 0 0 0/],
            [qw/0 0 0 0 0 0 0 0 0 0/],
            [qw/0 0 0 0 0 0 0 0 0 0/],
            [qw/0 0 0 0 0 0 0 0 0 0/],
        ];

    print_matrix($turn, $matrix);
    for (my $i=1; $i<$max_turn; $i++) {
        ($turn, $matrix) = next_step($turn, $matrix);
        print_matrix($turn, $matrix);
    }
}

main(41);

初投稿です。 長いコードですが、自分はC#なら富豪的に書きます。

間引きはわかりませんでした。 実装してみましたが、うまく動いてないような気がします・・・

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Drawing;
using System.Diagnostics;

public class LifeGame
{
    static void Main(string[] args)
    {
Start:
        Setting.Size = 10;      //格子サイズ
        Setting.InitRandomRate = 0.3; //人口密度
        Setting.Log = LogType.All;

        CellManager cm;

        Console.Clear();
        Console.WriteLine("seed = ?");
        int seed=0, wait = 50;
        int.TryParse(Console.ReadLine(), out seed);

        //---------------------------------------------------------------------
        cm = new CellManager(seed);
        int step = 0, step2 = 0;
        string last = string.Empty;//こうちゃくしたら止めるため
        while (true)
        {
            Console.WriteLine("seed = {0}---間引きなし:step={1}---間引きあり:step={2}", seed, step, step2);
            WriteSet(cm);
            step++;
            System.Threading.Thread.Sleep(wait);
            cm.ToNext();
            Console.Clear();
            if (cm.AliveCount == 0 || last == cm.EqualFlag)
                break;
            last = cm.EqualFlag;
        };

        Console.WriteLine("間引きあり : M/手動, M以外/自動");
        bool manual = Console.ReadKey().Key == ConsoleKey.M;
        Console.Clear();

        cm = new CellManager(seed);
        while (true)
        {
            Console.WriteLine("seed = {0}---間引きなし:step={1}---間引きあり:step={2}", seed, step, step2);
            cm.Cull_2();//間引き
            WriteSet(cm);
            step2++;
            if (manual)
                Console.ReadKey();
            else
                System.Threading.Thread.Sleep(wait);
            cm.ToNext();
            Console.Clear();
            if (cm.AliveCount == 0 || last == cm.EqualFlag)
                break;
            last = cm.EqualFlag;
        };
        Console.WriteLine("seed = {0}---間引きなし:step={1}---間引きあり:step={2}", seed, step, step2);

        //-----間引きしたときの生存数up率のn回の平均値を出してみるテスト。-------
        //int n = 100;
        //Setting.InitRandomRate = 0.3; //人口密度
        //Setting.Log = LogType.All;

        //Console.WriteLine("回数 = ?");
        //int.TryParse(Console.ReadLine(), out n);

        //var avg = Enumerable.Range(seed, n).Select(
        //    (seedValue, idx) =>
        //    {
        //        WriteState(string.Format("seed={0}", seedValue));
        //        WriteState("non cull");
        //        cm = new CellManager(seedValue);
        //        double nonCull = Test(cm);
        //        WriteState("cull");
        //        cm = new CellManager(seedValue);
        //        cm.Cull_2();
        //        double cull = Test(cm);

        //        var up = nonCull != 0 ? ((cull / nonCull) - 1.0d) * 100 : cull;
        //        WriteSimple(string.Format("間引きすると生存数は{0}% up", up));
        //        WriteState("**************************************************");
        //        if (double.IsInfinity(up))
        //            throw new InvalidOperationException();
        //        WriteNon(idx.ToString());
        //        return up;
        //    }
        //).Average();
        //WriteSimple(string.Format("平均 = {0}% up", avg));
        //---------------------------------------------------------------------

        Console.WriteLine("もう一度? y/n");
        if (Console.ReadKey().Key == ConsoleKey.Y)
            goto Start;
    }
    static int Test(CellManager cm)
    {
        WriteSet(cm);

        cm.ToNext();
        WriteState("next");
        WriteSet(cm);
        WriteState("-------------------");
        return cm.AliveCount;
    }
    static void WriteSet(CellManager cm)
    {
        WriteFigure(cm.CellLines);
        WriteState(string.Format("生存数={0} ", cm.AliveCount));
    }

    static void WriteFigure(IEnumerable<IGrouping<int,Cell>> data)
    {
        if ((Setting.Log & LogType.All) != LogType.All)
            return;
        foreach (var group in data)
        {
            var lineString = new string(group.Select(c => c.IsAlive ? '■' : '□').ToArray());
            Console.WriteLine(lineString);
        }
    }
    static void WriteNon(string text)
    {
        if (Setting.Log == LogType.Non) 
            Console.WriteLine(text);
    }
    static void WriteState(string text)
    {
        if((Setting.Log & LogType.State) == LogType.State)
            Console.WriteLine(text);
    }
    static void WriteSimple(string text)
    {
        if((Setting.Log & LogType.Simple) == LogType.Simple)
            Console.WriteLine(text);
    }
}

[Flags]
public enum LogType
{
    Non     = 0x000 ,   //表示しない(進捗のみ)
    Simple  = 0x001 ,   //最低限の数値
    State   = 0x011 ,   //詳細な数値
    All     = 0x111     //詳細な数値と図形
}
static public class Setting
{
    static public int Size { get; set; }
    static public int MatrixSize
    {
        get { return Size * Size; }
    }
    static public LogType Log { get; set; }
    static public double InitRandomRate { get; set; }
}
static public class CorrectExtension
{
    static public int CorrectValue;
    static public int Correct(this int a)
    {
        while (a < 0) a += Setting.Size;
        return a % Setting.Size;
    }
}
public class CellManager
{
    Random rand;
    List<Cell> data;

    public int AliveCount { get { return data.Count(cell => cell.IsAlive); } }
    public IEnumerable<Cell> Cells
    {
        get
        {
            return data.AsEnumerable();
        }
    }
    public IEnumerable<IGrouping<int, Cell>> CellLines
    {
        get
        {
            return Cells.GroupBy(c => Get(c).Y).OrderBy(gp => gp.Key);
        }
    }
    public string EqualFlag
    {
        get
        {
            return new string(data.Select(c => c.IsAlive ? '1' : '0').ToArray());
        }
    }

    public Cell newCell(bool alive)
    {
        return new Cell { Manager = this,IsAlive = alive };
    }

    public CellManager(int seed)
    {
        rand = new Random(seed);
        data = new List<Cell>();
        for (int i = 0; i < Setting.MatrixSize; i++)
        {
            data.Add(newCell(rand.NextDouble() < Setting.InitRandomRate));
        }
    }
    public CellManager(IEnumerable<bool> initData)
    {
        if (initData.Count() != Setting.MatrixSize)
            throw new ArgumentException();
        data = new List<Cell>(initData.Select(isAlive => newCell(isAlive )));
    }

    public void ToNext()
    {
        var nextData = data.Select(d => d.Next).ToArray();
        for (int i = 0; i < nextData.Length; i++)
        {
            data[i].IsAlive = nextData[i];
        }
    }

    // 間引き
    public void Cull_2()
    {
        //生きているやつをリストアップする。
        var aliveNoList = data.Where(cell => cell.IsAlive).Select(cell => data.IndexOf(cell)).ToArray();
        foreach (var no in aliveNoList)
        {
            //自分は次回生きてるか。
            var nextMe = data[no].Next;
            //現在の自分の回りの生存数
            var nowAround = data[no].AroundAliveCount;
            //次回の回りの生存数。
            var nowNext = data[no].Around.Count(c => c.Next);
            //死んでみる
            data[no].IsAlive = false;
            //自分が死んだ場合の次回の回りの生存数
            var testNext = data[no].Around.Count(c => c.Next);
            //回りの生存するが増えるなら死ぬ
            if (testNext > (nowNext + (nextMe ? 1 : 0)))
                continue;
            ////減らない(=同じ)で、4つ以上いたらどうせ死ぬから先に死ぬ
            // ※これやると、人口率0.3では下がりますが、人口率0.9ではこれがないと↑の間引きだけじゃうまくできない。
            //if (testNext == (nowNext + (nextMe ? 1 : 0)) && !nextMe)
            //    continue;
            data[no].IsAlive = true;
        }
    }

    // 間引き
    // 全パターンを調べてみる。遅すぎて論外でした。そもそも動くのかわかりません。
    public void Cull_1()
    {
        //生きているやつをリストアップする。
        var aliveNoList = data.Where(cell => cell.IsAlive).Select(cell => data.IndexOf(cell)).ToArray();
        int min = int.MaxValue;
        UInt64 minPattern = 0;//64個より多いとダメだけど、とりあえず気にしない。

        for (UInt64 patten = 0; patten <= UInt64.MaxValue; patten++)
        {
            //パターン対象を殺してみる
            for (int i = 0; i < aliveNoList.Count(); i++)
            {
                if ((patten&(((UInt64)1) << i)) != 0)
                {
                    data[aliveNoList[i]].IsAlive = false;
                }
            }
            //次回死んでいる数を調べ、最小ならパターン番号を覚える
            var a = data.Count(c => !c.Next);
            if (data.Count(c => !c.Next) < min)
            {
                min = a;
                minPattern = patten;
            }
            //パターン対象を戻す。
            for (int i = 0; i < aliveNoList.Count(); i++)
            {
                if ((patten & ((UInt64)1 << i)) != 0)
                {
                    data[aliveNoList[i]].IsAlive = true;
                }
            }
            //人数分のパターンが終わったので辞める。
            if ((patten & (((UInt64)1) << aliveNoList.Count())) != 0)
                break;
        }
        //最小パターンで殺す。
        for (int i = 0; i < aliveNoList.Count(); i++)
        {
            if ((minPattern & (((UInt64)1) << i)) != 0)
            {
                data[aliveNoList[i]].IsAlive = false;
            }
        }
    }

    public Point Get(Cell target)
    {
        int idx = data.IndexOf(target);
        if (idx < 0)
            throw new ArgumentException();

        return new Point(idx % Setting.Size, idx / Setting.Size);
    }
    public Cell Get(int x, int y)
    {
        return data[y.Correct() * Setting.Size + x.Correct()];
    }

    public Cell Get(Cell target, int offsetX, int offsetY)
    {
        var pos = Get(target);
        return Get(pos.X + offsetX, pos.Y + offsetY);
    }
}


public class Cell
{
    public CellManager Manager { get; set; }
    public bool IsAlive { get; set; }
    
    public IEnumerable<Cell> Around
    {
        get
        {
            for (int x = -1; x <= 1; x++)
            {
                for (int y = -1; y <= 1; y++)
                {
                    if (x == 0 && y == 0)
                        continue;
                    yield return Manager.Get(this, x, y);
                }
            }
        }
    }
    public int AroundAliveCount
    {
        get
        {
            return Around.Count(cell => cell.IsAlive);
        }
    }
    public bool Next
    {
        get
        {
            return IsAlive ?
                AroundAliveCount == 2 || AroundAliveCount == 3 :
                AroundAliveCount == 3;
        }
    }
}
Connection Machine用のLISP、*LISPのCL用シミュレータパッケージを
使用しています。
前回投稿したバージョンは、並列実行の構文を活用できていませんでしたが、
何となく構文が分かって来たので再挑戦してみました。

実行例(初期値をランダムに設定してループ表示):
;     DIMENSION 0 (X)  ----->
;
;0 1 1 1 1 1 1 1 1 1 
;1 0 1 0 1 1 1 0 0 1 
;1 1 0 1 1 1 1 0 0 0 
;0 0 1 1 1 1 0 0 1 0 
;1 1 0 0 1 0 1 1 0 0 
;1 0 1 1 1 0 1 1 0 1 
;1 0 0 0 1 0 1 1 1 1 
;0 1 1 0 0 0 1 1 1 0 
;0 0 0 0 1 1 0 0 0 1 
;0 1 1 1 1 0 0 0 1 0 
;
;     DIMENSION 0 (X)  ----->
;
;0 0 0 0 0 0 0 0 0 0 
;0 0 0 0 0 0 0 0 0 0 
;1 0 0 0 0 0 0 1 0 0 
;0 0 0 0 0 0 0 0 0 1 
;1 0 0 0 0 0 0 0 0 0 
;0 0 1 0 1 0 0 0 0 0 
;0 0 0 0 1 0 0 0 0 0 
;0 1 0 1 1 0 0 0 0 0 
;1 0 0 0 1 1 1 0 0 1 
;0 1 0 0 0 0 0 0 0 0 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
(defpackage :doukaku-126 (:use :cl :*lisp))
(in-package :doukaku-126)
(*cold-boot :initial-dimensions '(10 10))

(defconstant +alive+ 1)
(defconstant +dead+ 0)

(defun gen-next!! (pvar)
  (let ((env (count!! +alive+
              (vector!!
               (news!! pvar -1 -1) (news!! pvar -1  0) (news!! pvar -1  1)
               (news!! pvar  0 -1) (news!! pvar  0  1) 
               (news!! pvar  1 -1) (news!! pvar  1  0) (news!! pvar  1  1)))))
    (cond!! ((and!! (eql!! +dead+ pvar) (=!! env 3)) +alive+)
            ((and!! (eql!! +alive+ pvar) (<=!! 2 env 3)) +alive+)
            (t!! +dead+))))

;; 実行例(初期値をランダムに設定してループ表示):
(loop :for gen = (truncate!! (random!! 10) 5) :then (gen-next!! gen)
      :do (ppp gen) 
      :unless (y-or-n-p) :do (return))

とりあえずWikiPediaでルールを読んで23/3を組んでみました。末端のループもやっています。 ライフゲームは昔から動いてるところは見たことあっても、実際に書いてみたことはなかったので楽しめました...間引きはこれから勉強します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
module Main
    where

import Data.Array

type Point = (Int, Int)
type Size = (Int, Int)
type TwoDArray = (Size, Array Int Char)

glider = ".........." ++
     "..X......." ++ 
     ".X........" ++ 
     ".XXX......" ++ 
     ".........." ++
     ".........." ++
     ".........." ++
     ".........." ++
     ".........." ++
     ".........."

makeArray :: Size -> [Char] -> TwoDArray
makeArray  sz@(cx, cy) str = (sz, listArray (0, cx * cy - 1) str)

ptToIdx :: Size -> Point -> Int
ptToIdx (cx, cy) (x, y) = (y * cx) + x

fetch :: TwoDArray -> Point -> Char
fetch (sz, rg) pt = rg!(ptToIdx sz pt)

surrounding = [(x, y) | x <- [-1..1], y <-[-1..1], x /= 0 || y /= 0]

addPt :: Point -> Size -> Point -> Point
addPt (x1, y1) (cx, cy) (x2, y2) = ((x1 + x2) `mod` cx, (y1 + y2) `mod` cy)

getSurroundingPts :: Point -> Size -> [Point]
getSurroundingPts pt sz = map (addPt pt sz) surrounding

countSurroundingLife :: TwoDArray -> Point -> Int
countSurroundingLife td@(sz, rg) pt  = 
    length $ filter (/='.') $ map (fetch td) $ getSurroundingPts pt sz

allPoints :: Size -> [Point]
allPoints (cx, cy) = [(x, y) | y <- [0..(cx - 1)], x <- [0..(cy - 1)]]

birthDeath :: Char -> Int -> Char
birthDeath ch c
    | c == 3 && ch == '.' = 'X'
    | ch == 'X' && (c == 2 || c == 3) = 'X'
    | otherwise = '.'

doGen :: TwoDArray -> Point -> Char
doGen rg pt = birthDeath (fetch rg pt) (countSurroundingLife rg pt)

nextGen :: TwoDArray -> TwoDArray
nextGen td@(sz, rg) = makeArray sz $ map (doGen td) (allPoints sz)

lifes :: TwoDArray -> [TwoDArray]
lifes td = [td] ++ (lifes (nextGen td))

dumpRow :: TwoDArray -> Int -> IO()
dumpRow ((cx, cy), rg) iy = putStrLn $ map (rg!) $ [(iy * cx)..((iy * cx) + cx - 1)]

dumpMap :: TwoDArray -> Int -> IO()
dumpMap td@(size@(cx, cy), rg) iGen = do
    putStrLn $ "Generation " ++ (show iGen)
    mapM (dumpRow td) [0..(cy-1)]
    putStrLn ""

doLife :: [(Int, TwoDArray)] -> IO()
doLife [] = return ()
doLife (x@(iGen, rg):xs) = do
    dumpMap rg iGen
    doLife xs

main :: IO()
main = do
    doLife $ zip [1..20] (lifes start)
    where
        start = makeArray sz glider
        sz = (10, 10)

ライフゲームは初めて実装しましたが、面白いものですねえ。

LifeGame::Board#drawメソッドが気持ち悪いのですが、とりあえず投稿します。本当はLifeGame::Board#to_sの結果を画面に描画するほうが良いのですが‥‥。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env ruby

require 'curses'

module LifeGame
  class Board
    def initialize(board)
      @board = board
    end

    def width
      @board.map {|i| i.size }.max
    end

    def height
      @board.size
    end

    def check(x, y)
      @board[y][x]
    end

    def set(x, y, cell)
      @board[y][x] = cell
    end

    def draw(window)
      (1..(height)).each do |i|
        window.setpos(i, 1)
        window.addstr(@board[i - 1].join)
        window.refresh
      end
    end

    def to_s
      @board.map {|i| i.join }.join("\n")
    end

    def next
      result = Board.new(Array.new(height).map { Array.new(width) })
      (-1..(height - 2)).each do |j|
        (-1..(width - 2)).each do |i|
          result.set(i, j, next_life(check(i, j),
            [check(i - 1, j - 1),
             check(i, j - 1),
             check(i + 1, j - 1),
             check(i - 1, j),
             check(i + 1, j),
             check(i - 1, j + 1),
             check(i, j +1 ),
             check(i + 1, j + 1)]))
        end
      end
      result
    end

    private
    def next_life(cell, arrownd = [])
      case
      when (cell == ' ') && (arrownd.grep(/\*/).size == 3)
        '*'
      when (cell == '*') && (arrownd.grep(/\*/).size.between?(2, 3))
        '*'
      else
        ' '
      end
    end
  end
end

if __FILE__ == $0
  begin
    board = LifeGame::Board.new([
      [' ', '*', ' ', ' ', ' ', ' ', '*', '*', '*', ' '],
      [' ', ' ', ' ', ' ', '*', ' ', ' ', '*', '*', ' '],
      [' ', ' ', ' ', '*', ' ', ' ', '*', ' ', '*', ' '],
      ['*', ' ', '*', '*', ' ', ' ', '*', ' ', ' ', ' '],
      [' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', '*', ' '],
      ['*', ' ', ' ', ' ', '*', ' ', '*', '*', ' ', '*'],
      [' ', '*', ' ', ' ', ' ', ' ', '*', ' ', ' ', ' '],
      [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '*'],
      ['*', ' ', ' ', ' ', ' ', ' ', '*', ' ', ' ', '*'],
      [' ', ' ', ' ', ' ', '*', '*', ' ', ' ', '*', ' ']])
    time = 0
    window = Curses::Window.new(Curses.lines, Curses.cols, 0, 0)
    sub_window = window.subwin(board.height + 2, board.width + 2, 2, 2)
    sub_window.box(?|, ?-, ?+)
    loop do
      window.setpos(0, 0)
      window.addstr("t = #{time}")
      board.draw(sub_window)
      window.getch
      time += 1
      board = board.next
    end
  ensure
    window.close
  end
end

計算結果をJTextAreaに表示します。 sawatさんのコードとは異なり、格子状の平面を独自に定義したFieldクラスによって表現しています。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Doukaku126.java

import java.awt.*;
import java.util.*;
import javax.swing.*;

public class Doukaku126 extends JFrame implements Runnable {
    Field field;
    JTextArea textArea;

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }

    public Doukaku126() {
        super("ライフゲーム(どう書く?org #126)");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        field = new Field(10, 10);
        field.makeLifes(0.3);

        textArea = new JTextArea();
        textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
        add(textArea, BorderLayout.CENTER);

        Thread t = new Thread(this);
        t.start();
    }
    /**
     * mainスレッドからGUIを構築しないために利用するメソッド
     * 参考->http://d.hatena.ne.jp/torutk/20060928#p2
     */
    private static void createAndShowGui() {
        Doukaku126 frame = new Doukaku126();
        frame.setSize(240, 240);
        frame.setVisible(true);
    }
    public void run() {
        StringBuffer sb = new StringBuffer();
        try {
            while (true) {
                field.print(sb);
                textArea.setText(sb.toString());
                field.next();
                Thread.sleep(200);
            }
        } catch (Exception e) {

        }

    }
    final class Field {
        private boolean[][] nowLife, nextLife, life;

        private int width, height;

        /**
         * フィールドのコンストラクタ
         * 
         * @param width
         *            フィールドの幅
         * @param height
         *            フィールドの高さ
         */
        public Field(final int width, final int height) {
            nowLife = new boolean[width][height];
            nextLife = new boolean[width][height];
            this.width = width;
            this.height = height;
        }

        /**
         * フィールドに生命を生成する(ランダム)
         * 
         * @param percent
         *            1つのセルに生命が誕生する確率[0.0,1.0]
         */
        public void makeLifes(final double percent) {
            Random random = new Random();
            for (int y = 0; y < height; ++y) {
                for (int x = 0; x < width; ++x) {
                    nowLife[x][y] = random.nextDouble() < percent;
                }
            }
        }

        /**
         * 時間を進め、生命の状態を変化させる
         */
        public void next() {
            for (int y = 0; y < height; ++y) {
                for (int x = 0; x < width; ++x) {
                    nextLife[x][y] = nextLife(nowLife[x][y], aroundLifesNum(x, y));
                }
            }
            // 計算結果をコピー
/*            for (int x = 0; x < width; ++x) {
                System.arraycopy(nextLife[x], 0, nowLife[x], 0, height);
            }
/*/
            tmpLife = nowLife;
            nowLife = nextLife;
            nextLife = tmpLife;
//*/
        }

        /**
         * 現在の生命の状態と周囲の生命数から、次の生命の状態を調べる
         * 
         * @param nowLife
         *            現在の生命の状態
         * @param numLifes
         *            周囲の生命数
         * @return 次の生命の状態
         */
        private boolean nextLife(final boolean nowLife, final int numLifes) {
            return (nowLife && (numLifes == 2 || numLifes == 3))
                    || (!nowLife && numLifes == 3);
        }

        /**
         * 周囲の生命の数を返す
         */
        private int aroundLifesNum(final int x, final int y) {
            int num = 0;
            for (int i = 0; i < 8; ++i) {
                if (aroundLife(x, y, i)) {
                    ++num;
                }
            }
            return num;
        }

        // posと場所は次のように対応
        // 0 1 2
        // 7 * 3
        // 6 5 4
        private boolean aroundLife(int x, int y, final int pos) {
            if (pos < 3) {
                --y;
            } else if (4 <= pos && pos <= 6) {
                ++y;
            }
            if (pos == 0 || pos == 6 || pos == 7) {
                --x;
            } else if (2 <= pos && pos <= 4) {
                ++x;
            }
            return nowLife[(x+width)%width][(y+height)%height];
        }

        /**
         * 自分自身の文字表現をStringBufferへ代入
         */
        public void print(final StringBuffer sb) {
            sb.delete(0, sb.length());
            for (int y = 0; y < height; ++y) {
                for (int x = 0; x < width; ++x) {
                    sb.append(nowLife[x][y] ? "[*]" : "[ ]");
                }
                sb.append("\n");
            }
        }
    }
}
コンソール専用化と思っていたら
エスケープシーケンスってVT100エミュレーション下では
ちゃんと機能するんですね。
20へぇ~

Cっぽくポインタを活用してみました。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>

typedef struct tagCell
{
    int alive; // 今の状態
    int life;  // 次の状態
    struct tagCell *around[9]; // 自分の周囲(自分含む)
} CELL;

static const char *CELL_CHAR[] = { "□", "■" };

#define HEIGHT (10)
#define WIDTH  (10)
static CELL cells[ HEIGHT ][ WIDTH ];

/* 初期パターン (0:死 /1:生) */
// お題サンプル(池になって終わり)
static const int graph_paturn1[ HEIGHT * WIDTH ] =
{
//         1   2   3   4   5   6   7   8   9  10 
/*  1 */   0,  1,  0,  0,  0,  0,  1,  1,  1,  0,
/*  2 */   0,  0,  0,  0,  1,  0,  0,  1,  1,  0,
/*  3 */   0,  0,  0,  1,  0,  0,  1,  0,  1,  0,
/*  4 */   1,  0,  1,  1,  0,  0,  1,  0,  0,  0,
/*  5 */   0,  1,  0,  0,  0,  0,  0,  0,  1,  0,
/*  6 */   1,  0,  0,  0,  1,  0,  1,  1,  0,  1,
/*  7 */   0,  1,  0,  0,  0,  0,  1,  0,  0,  0,
/*  8 */   0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
/*  9 */   1,  0,  0,  0,  0,  0,  1,  0,  0,  1,
/* 10 */   0,  0,  0,  0,  1,  1,  0,  0,  1,  0
};

// 基本パターン固定型
static const int graph_paturn2[ HEIGHT * WIDTH ] =
{
//         1   2   3   4   5   6   7   8   9  10 
/*  1 */   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
/*  2 */   0,  1,  0,  0,  0,  0,  0,  1,  0,  0,
/*  3 */   0,  1,  0,  0,  0,  1,  0,  0,  1,  0,
/*  4 */   0,  1,  0,  0,  0,  1,  0,  0,  1,  0,
/*  5 */   0,  0,  0,  0,  0,  0,  1,  0,  0,  0,
/*  6 */   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
/*  7 */   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
/*  8 */   0,  0,  1,  0,  0,  0,  0,  0,  0,  0,
/*  9 */   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
/* 10 */   0,  0,  0,  0,  0,  0,  0,  0,  0,  0
};

inline void CLS(void){  printf("\x1b[2J"); }
inline void LOCATE(int x, int y){ printf("\x1b[%d;%dH", y, x); }
inline void STORE_LOCATE(void){ printf("\x1b[s"); }
inline void RESTORE_LOCATE(void){ printf("\x1b[u"); }

/* 指定した座標のセル取得 */
inline int getCell(CELL **out, int x, int y)
{
    assert(out != NULL );

    /* 座標の正規化 */
    y %= HEIGHT; if( y < 0 ){ y = HEIGHT + y; }
    x %= WIDTH;  if( x < 0 ){ x = WIDTH  + x; }

    /*  */
    *out = &cells[y][x];
    assert(*out != NULL );
    return 0;
}

/* 現在の状態から次世代の状態を設定する */
int set_next_life(struct tagCell *cell)
{
    int score;
    assert(cell != NULL );
    score = cell->around[0]->alive   + cell->around[1]->alive + cell->around[2]->alive
            + cell->around[3]->alive                          + cell->around[5]->alive
            + cell->around[6]->alive + cell->around[7]->alive + cell->around[8]->alive;
    switch( score )
    {
        case 2: // 維持
            break;
        case 3: // 誕生
            cell->life = 1;
            break;
        default: // 死亡
            cell->life = 0;
            break;
    }
    return 0;
}

/* 初期化いろいろ */
int initialize(void)
{
    static const int *graph = graph_paturn1; // 初期配置

    struct tagCell   *cell;

    /* スクリーンの初期化 */
    CLS(); LOCATE(1,3);

    /* セルの初期化 */
    memset( &cells, 0, sizeof(cells) );
    for( int h=0; h < HEIGHT; h ++ )
    {
        for( int w=0; w < WIDTH; w ++ )
        {
            cell = &cells[ h ][ w ];
            cell->alive = *graph++;
            cell->life  = cell->alive;
            /* 周囲セルの設定 */
            getCell(&cell->around[0], w-1, h-1);
            getCell(&cell->around[1], w  , h-1);
            getCell(&cell->around[2], w+1, h-1);
            getCell(&cell->around[3], w-1, h  );
            getCell(&cell->around[4], w  , h  ); //自分自身
            getCell(&cell->around[5], w+1, h  );
            getCell(&cell->around[6], w-1, h+1);
            getCell(&cell->around[7], w  , h+1);
            getCell(&cell->around[8], w+1, h+1);
        }
    }
    return 0;
}

/* 現在の状態を表示 */
int print_cells(void)
{
    struct tagCell *cell;
    for( int h=0; h < HEIGHT; h ++ )
    {
        for( int w=0; w < WIDTH; w ++ )
        {
            cell = &cells[ h ][ w ];
//          printf("[%c]", (cell->alive == 1)?'*':' ');
            printf("%s", CELL_CHAR[ cell->alive ] );
            cell->alive = cell->life; // 表示したので次世代の状態を反映する
        }
        printf("\n");
    }
    return 0;
}

/*  */
void play(int frame)
{
    struct timespec interval = 
    { 
        .tv_sec = 0,
        .tv_nsec = 125000000
    };

    STORE_LOCATE();
    for( int t=0; t<=frame || frame==-1; t++ )
    {
        RESTORE_LOCATE();
        /* 表示前に次の状態を計算 */
        for( int h=0; h < HEIGHT; h ++ )
        {
            for( int w=0; w < WIDTH; w ++ )
            {
                set_next_life( &cells[ h ][ w ] );
            }
        }

        /* 表示 */
        printf("t=%d\n", t);
        print_cells();

        /* ディレイ */
        nanosleep(&interval, NULL);
    }
}

int main(int argc, char *argv[])
{
    initialize();
    play( (argc>1)?atoi( argv[1] ):-1 );
    return 0;
}

グライダーが動いているので大丈夫だと思います。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import time

X_MAX = 9
Y_MAX = 9

def lefx(x,mx):
    if (x - 1) < 0:
        return mx
    else:
        return x - 1

def rigx(x,mx):
    if (x + 1) > mx:
        return 0
    else:
        return x + 1

def up_y(y,my):
    if (y - 1) < 0:
        return my
    else:
        return y - 1

def dowy(y,my):
    if (y + 1) > my:
        return 0
    else:
        return y + 1

def list_search(motherlist):
    buflist = [[0] * len(motherlist) for i in range(len(motherlist))]
    #range(9) = [0,1,2,3,4,5,6,7,8]
    #range(9+1) = [0,1,2,3,4,5,6,7,8,9]
    for x in range(X_MAX+1):
        for y in range(Y_MAX+1):
            if motherlist[lefx(x,X_MAX)][up_y(y,Y_MAX)] == 1:
                buflist[x][y] += 1
            if motherlist[lefx(x,X_MAX)][y] == 1:
                buflist[x][y] += 1
            if motherlist[lefx(x,X_MAX)][dowy(y,Y_MAX)] == 1:
                buflist[x][y] += 1
            if motherlist[x][up_y(y,Y_MAX)] == 1:
                buflist[x][y] += 1
            if motherlist[x][dowy(y,Y_MAX)] == 1:
                buflist[x][y] += 1
            if motherlist[rigx(x,X_MAX)][up_y(y,Y_MAX)] == 1:
                buflist[x][y] += 1
            if motherlist[rigx(x,X_MAX)][y] == 1:
                buflist[x][y] += 1
            if motherlist[rigx(x,X_MAX)][dowy(y,Y_MAX)] == 1:
                buflist[x][y] += 1
    return buflist

def list_weight(motherlist,buflist):
    buflist2 = [[0]*len(motherlist) for i in range(len(motherlist))]
    for x in range(X_MAX+1):
        for y in range(Y_MAX+1):
            if buflist[x][y] == 3 and motherlist[x][y] == 0:
                buflist2[x][y] = 1
            if buflist[x][y] == 2 and motherlist[x][y] == 1:
                buflist2[x][y] = 1
            if buflist[x][y] == 3 and motherlist[x][y] == 1:
                buflist2[x][y] = 1

    return buflist2

def main(motherlist,count,sleep):
    
    while(count > 0):

        for i in range(len(motherlist)):
            print(motherlist[i])
        
        print('\n')
        motherlist = list_weight(motherlist,list_search(motherlist))
        time.sleep(sleep)
        count -= 1


if __name__ == '__main__':
    testlist = [[0,0,0,0,0,0,0,0,0,0] for i in range(10)]
    testlist[5][6] = 1
    testlist[6][7] = 1
    testlist[7][5] = 1
    testlist[7][6] = 1
    testlist[7][7] = 1
    main(testlist,100,1)
PostScript で書いてみました。 このままプリンタに流すと1世代1枚の紙を浪費しますのでご注意下さい。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
!PS

%---------------- Initialize -----------
/TestMap [ % 10x10
   0 1 0 0 0 0 1 1 1 0
   0 0 0 0 1 0 0 1 1 0
   0 0 0 1 0 0 1 0 1 0
   1 0 1 1 0 0 1 0 0 0
   0 1 0 0 0 0 0 0 1 0
   1 0 0 0 1 0 1 1 0 1
   0 1 0 0 0 0 1 0 0 0
   0 0 0 0 0 0 0 0 0 1
   1 0 0 0 0 0 1 0 0 1
   0 0 0 0 1 1 0 0 1 0
] def
/RandomMap {
    realtime srand
    [1 1 MapSize2 { pop rand 1000 mod 300 gt {0} {1} ifelse } for]
} def

/OrgMap { TestMap } def
/MapSizeX 10 def
/MapSizeY 10 def
/Loop 150 def

%              0    1     2     3     4    5    6     7      8    
/RuleBorn [ false false false  true false false false false false ] def
/RuleKeep [ false false  true  true false false false false false ] def

% ----Printout Size-------------------
/MapWidth 500 def
/MapHeight 500 def
/MapOffsetX 20 def
/MapOffsetY 70 def
% -------------------------------------
/Times-Roman findfont 16 scalefont setfont
/MapSizeX2 MapSizeX 2 add def
/MapSize2 MapSizeX MapSizeY mul def
/MapSize3 MapSizeX2 MapSizeY mul def

/Vect [-1 MapSizeX2 sub 0 MapSizeX2 sub 1 MapSizeX2 sub -1 1 MapSizeX2 1 sub M\
apSizeX2 MapSizeX2 1 add] def

/DispMap {
    20 20 moveto (Life Game: Stage=) show
    10 string cvs show
    /Map exch def
    /VX MapWidth MapSizeX idiv def
    /VY MapHeight MapSizeY idiv def
    0 1 MapSizeY 1 sub {
        /y exch def
        0 1 MapSizeX 1 sub {
            /x exch def
            x VX mul MapOffsetX add
            y VY mul -1 mul MapHeight add MapOffsetY add moveto
            VX 0 rlineto 0 VY rlineto 0 VX sub 0 rlineto closepath
            Map x y MapSizeX2 mul add 1 add get 1 eq { fill } { stroke } ifels\
e
        } for
    } for
} def

/ExpandMap {
    /Offset exch def
    /Width MapSizeX Offset 2 mul add def
    /Map exch def
    [
        0 1 MapSizeY 1 sub {
            Width mul Offset add /v exch def
            Map v MapSizeX add 1 sub get
            0 1 MapSizeX 1 sub {
                v add Map exch get
            } for
            Map v get
        } for
    ]
} def

/NewStage {
    1 ExpandMap
    /Map exch def
    [
    0 1 MapSize3 1 sub {
        /v exch def
        /count 0 def
        0 1 7 {
            Vect exch get
            v add MapSize3 add MapSize3 mod /vx exch def
            /count count Map vx get add def
        } for
        0
        Map v get 0 eq {RuleBorn count get { pop 1 } if }
            {RuleKeep count get { pop 1 } if } ifelse
    } for
    ]
} def

/OrgMap OrgMap 0 ExpandMap def
0 1 Loop {
    OrgMap exch DispMap showpage
    /OrgMap OrgMap NewStage def
} for
投稿とちりました。
1行目先頭に "%" が必要、41、57行は継続行です。

お題のサンプルは一部違う