Reformatting for consistency.
[cellular-automata.git] / 003 / src / life.erl
1 -module(life).
2
3 -export([bang/1]).
4
5
6 -define(CHAR_DEAD, 32). % " "
7 -define(CHAR_ALIVE, 111). % "o"
8 -define(CHAR_BAR, 45). % "-"
9
10 -define(INTERVAL, 100).
11
12
13 -record(state, {x :: non_neg_integer()
14 ,y :: non_neg_integer()
15 ,n :: pos_integer()
16 ,bar :: nonempty_string()
17 ,board :: array()
18 ,gen_count :: pos_integer()
19 ,gen_duration :: non_neg_integer()
20 ,print_time :: non_neg_integer()
21 }).
22
23
24 %% ============================================================================
25 %% API
26 %% ============================================================================
27
28 bang(Args) ->
29 [X, Y] = [atom_to_integer(A) || A <- Args],
30 {Time, Board} = timer:tc(fun() -> init_board(X, Y) end),
31 State = #state{x = X
32 ,y = Y
33 ,n = X * Y
34 ,bar = [?CHAR_BAR || _ <- lists:seq(1, X)]
35 ,board = Board
36 ,gen_count = 1 % Consider inital state to be generation 1
37 ,gen_duration = Time
38 ,print_time = 0 % There was no print time yet
39 },
40 life_loop(State).
41
42
43 %% ============================================================================
44 %% Internal
45 %% ============================================================================
46
47 life_loop(
48 #state{x = X
49 ,y = Y
50 ,n = N
51 ,bar = Bar
52 ,board = Board
53 ,gen_count = GenCount
54 ,gen_duration = Time
55 ,print_time = LastPrintTime
56 }=State) ->
57
58 {PrintTime, ok} = timer:tc(
59 fun() ->
60 do_print_screen(Board, Bar, X, Y, N, GenCount, Time, LastPrintTime)
61 end
62 ),
63
64 {NewTime, NewBoard} = timer:tc(
65 fun() ->
66 next_generation(X, Y, Board)
67 end
68 ),
69
70 NewState = State#state{board = NewBoard
71 ,gen_count = GenCount + 1
72 ,gen_duration = NewTime
73 ,print_time = PrintTime
74 },
75
76 timer:sleep(?INTERVAL),
77 life_loop(NewState).
78
79
80 do_print_screen(Board, Bar, X, Y, N, GenCount, Time, PrintTime) ->
81 ok = do_print_status(Bar, X, Y, N, GenCount, Time, PrintTime),
82 ok = do_print_board(Board).
83
84
85 do_print_status(Bar, X, Y, N, GenCount, TimeMic, PrintTimeMic) ->
86 TimeSec = TimeMic / 1000000,
87 PrintTimeSec = PrintTimeMic / 1000000,
88 ok = io:format("~s~n", [Bar]),
89 ok = io:format(
90 "X: ~b Y: ~b CELLS: ~b GENERATION: ~b DURATION: ~f PRINT TIME: ~f~n",
91 [X, Y, N, GenCount, TimeSec, PrintTimeSec]
92 ),
93 ok = io:format("~s~n", [Bar]).
94
95
96 do_print_board(Board) ->
97 RowStrings = array:to_list(
98 array:map(
99 fun(_, Row) ->
100 array:to_list(
101 array:map(
102 fun(_, State) ->
103 state_to_char(State)
104 end,
105 Row
106 )
107 )
108 end,
109 Board
110 )
111 ),
112
113 ok = lists:foreach(
114 fun(RowString) ->
115 ok = io:format("~s~n", [RowString])
116 end,
117 RowStrings
118 ).
119
120
121 state_to_char(0) -> ?CHAR_DEAD;
122 state_to_char(1) -> ?CHAR_ALIVE.
123
124
125 next_generation(W, H, Board) ->
126 array:map(
127 fun(Y, Row) ->
128 array:map(
129 fun(X, State) ->
130 Neighbors = filter_offsides(H, W, neighbors(X, Y)),
131 States = neighbor_states(Board, Neighbors),
132 LiveNeighbors = lists:sum(States),
133 new_state(State, LiveNeighbors)
134 end,
135 Row
136 )
137 end,
138 Board
139 ).
140
141
142 new_state(1, LiveNeighbors) when LiveNeighbors < 2 -> 0;
143 new_state(1, LiveNeighbors) when LiveNeighbors < 4 -> 1;
144 new_state(1, LiveNeighbors) when LiveNeighbors > 3 -> 0;
145 new_state(0, LiveNeighbors) when LiveNeighbors =:= 3 -> 1;
146 new_state(State, _LiveNeighbors) -> State.
147
148
149 neighbor_states(Board, Neighbors) ->
150 [array:get(X, array:get(Y, Board)) || {X, Y} <- Neighbors].
151
152
153 filter_offsides(H, W, Coordinates) ->
154 [{X, Y} || {X, Y} <- Coordinates, is_onside(X, Y, H, W)].
155
156
157 is_onside(X, Y, H, W) when (X >= 0) and (Y >= 0) and (X < W) and (Y < H) -> true;
158 is_onside(_, _, _, _) -> false.
159
160
161 neighbors(X, Y) ->
162 [{X + OffX, Y + OffY} || {OffX, OffY} <- offsets()].
163
164
165 offsets() ->
166 [offset(D) || D <- directions()].
167
168
169 offset('N') -> { 0, -1};
170 offset('NE') -> { 1, -1};
171 offset('E') -> { 1, 0};
172 offset('SE') -> { 1, 1};
173 offset('S') -> { 0, 1};
174 offset('SW') -> {-1, 1};
175 offset('W') -> {-1, 0};
176 offset('NW') -> {-1, -1}.
177
178
179 directions() ->
180 ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].
181
182
183 init_board(X, Y) ->
184 array:map(fun(_, _) -> init_row(X) end, array:new(Y)).
185
186
187 init_row(X) ->
188 array:map(fun(_, _) -> init_cell_state() end, array:new(X)).
189
190
191 init_cell_state() ->
192 crypto:rand_uniform(0, 2).
193
194
195 atom_to_integer(Atom) ->
196 list_to_integer(atom_to_list(Atom)).
This page took 0.048673 seconds and 4 git commands to generate.