Don't sleep longer than necessary to meet the interval.
[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(GEN_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 NewTimeMil = NewTime / 1000,
77 NextGenDelay = round(?GEN_INTERVAL - NewTimeMil),
78 timer:sleep(NextGenDelay),
79
80 life_loop(NewState).
81
82
83 do_print_screen(Board, Bar, X, Y, N, GenCount, Time, PrintTime) ->
84 ok = do_print_status(Bar, X, Y, N, GenCount, Time, PrintTime),
85 ok = do_print_board(Board).
86
87
88 do_print_status(Bar, X, Y, N, GenCount, TimeMic, PrintTimeMic) ->
89 TimeSec = TimeMic / 1000000,
90 PrintTimeSec = PrintTimeMic / 1000000,
91 ok = io:format("~s~n", [Bar]),
92 ok = io:format(
93 "X: ~b Y: ~b CELLS: ~b GENERATION: ~b DURATION: ~f PRINT TIME: ~f~n",
94 [X, Y, N, GenCount, TimeSec, PrintTimeSec]
95 ),
96 ok = io:format("~s~n", [Bar]).
97
98
99 do_print_board(Board) ->
100 % It seems that just doing a fold should be faster than map + to_list
101 % combo, but, after measuring several times, map + to_list has been
102 % consistently (nearly twice) faster than either foldl or foldr.
103 RowStrings = array:to_list(
104 array:map(
105 fun(_, Row) ->
106 array:to_list(
107 array:map(
108 fun(_, State) ->
109 state_to_char(State)
110 end,
111 Row
112 )
113 )
114 end,
115 Board
116 )
117 ),
118
119 ok = lists:foreach(
120 fun(RowString) ->
121 ok = io:format("~s~n", [RowString])
122 end,
123 RowStrings
124 ).
125
126
127 state_to_char(0) -> ?CHAR_DEAD;
128 state_to_char(1) -> ?CHAR_ALIVE.
129
130
131 next_generation(W, H, Board) ->
132 array:map(
133 fun(Y, Row) ->
134 array:map(
135 fun(X, State) ->
136 Neighbors = filter_offsides(H, W, neighbors(X, Y)),
137 States = neighbor_states(Board, Neighbors),
138 LiveNeighbors = lists:sum(States),
139 new_state(State, LiveNeighbors)
140 end,
141 Row
142 )
143 end,
144 Board
145 ).
146
147
148 new_state(1, LiveNeighbors) when LiveNeighbors < 2 -> 0;
149 new_state(1, LiveNeighbors) when LiveNeighbors < 4 -> 1;
150 new_state(1, LiveNeighbors) when LiveNeighbors > 3 -> 0;
151 new_state(0, LiveNeighbors) when LiveNeighbors =:= 3 -> 1;
152 new_state(State, _LiveNeighbors) -> State.
153
154
155 neighbor_states(Board, Neighbors) ->
156 [array:get(X, array:get(Y, Board)) || {X, Y} <- Neighbors].
157
158
159 filter_offsides(H, W, Coordinates) ->
160 [{X, Y} || {X, Y} <- Coordinates, is_onside(X, Y, H, W)].
161
162
163 is_onside(X, Y, H, W) when (X >= 0) and (Y >= 0) and (X < W) and (Y < H) -> true;
164 is_onside(_, _, _, _) -> false.
165
166
167 neighbors(X, Y) ->
168 [{X + OffX, Y + OffY} || {OffX, OffY} <- offsets()].
169
170
171 offsets() ->
172 [offset(D) || D <- directions()].
173
174
175 offset('N') -> { 0, -1};
176 offset('NE') -> { 1, -1};
177 offset('E') -> { 1, 0};
178 offset('SE') -> { 1, 1};
179 offset('S') -> { 0, 1};
180 offset('SW') -> {-1, 1};
181 offset('W') -> {-1, 0};
182 offset('NW') -> {-1, -1}.
183
184
185 directions() ->
186 ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].
187
188
189 init_board(X, Y) ->
190 array:map(fun(_, _) -> init_row(X) end, array:new(Y)).
191
192
193 init_row(X) ->
194 array:map(fun(_, _) -> init_cell_state() end, array:new(X)).
195
196
197 init_cell_state() ->
198 crypto:rand_uniform(0, 2).
199
200
201 atom_to_integer(Atom) ->
202 list_to_integer(atom_to_list(Atom)).
This page took 0.074606 seconds and 4 git commands to generate.