-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlife_forms.erl
95 lines (75 loc) · 1.5 KB
/
life_forms.erl
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
-module(life_forms).
-compile(export_all).
%% Sample lifeforms (from Wikipedia) %%
% Still life:
block() ->
[
[x,x],
[x,x]
].
beehive() ->
[
[o,x,x,o],
[x,o,o,x],
[o,x,x,o]
].
loaf() ->
[
[o,x,x,o],
[x,o,o,x],
[o,x,o,x],
[o,o,x,o]
].
boat() ->
[
[x,x,o],
[x,o,x],
[o,x,o]
].
% Oscillators
blinker() ->
[ [x,x,x] ].
toad() ->
[
[o,x,x,x],
[x,x,x,o]
].
beacon() ->
[
[x,x,o,o],
[x,x,o,o],
[o,o,x,x],
[o,o,x,x]
].
% Insert Pulsar here if you feel like typing it all out :)
% Spaceships
glider() ->
[
[o,o,x],
[x,o,x],
[o,x,x]
].
%% Utility %%
% Add a life form (in the form of a matrix, as above)
% with the specified coordinates as the top-left
add(Matrix, {X, Y}) ->
lists:foldl(fun add_row/2, {X, Y}, Matrix),
ok.
add_row(Row, {X, Y}) ->
lists:foldl(fun add_cell/2, {X, Y}, Row),
{X, Y+1}.
% "Add" an empty cell (do nothing, just increment the column counter)
add_cell(o, {X, Y}) -> {X+1, Y};
% Add a full cell:
add_cell(x, P={X, Y}) ->
cell_store:set_cell(P, true),
{X+1, Y}.
% Transformations that can be applied to life forms
mirror_x(Matrix) -> [lists:reverse(L) || L <- Matrix].
mirror_y(Matrix) -> lists:reverse(Matrix).
rotate_l(Matrix) -> rotate_l(Matrix, []).
rotate_r(Matrix) -> lists:reverse([lists:reverse(Row) || Row <- rotate_l(Matrix, [])]).
% Helper functions (not for external use):
rotate_l(Matrix, Acc) when hd(Matrix) =:= [] -> Acc;
rotate_l(Matrix, Acc) ->
rotate_l([tl(Row) || Row <- Matrix], [[hd(Row) || Row <- Matrix] | Acc]).