6 -define(CHAR_DEAD, 32). % " "
7 -define(CHAR_ALIVE, 111). % "o"
8 -define(CHAR_BAR, 45). % "-"
10 -define(INTERVAL, 100).
13 -record(state, {x :: non_neg_integer()
14 ,y :: non_neg_integer()
15 ,n :: non_neg_integer()
17 ,board=array:new() :: array()
18 ,gen_count :: non_neg_integer()
19 ,gen_duration :: non_neg_integer()
23 %% ============================================================================
25 %% ============================================================================
28 [X, Y] = [atom_to_integer(A) || A <- Args],
29 {Time, Board} = timer:tc(fun() -> init_board(X, Y) end),
33 ,bar = [?CHAR_BAR || _ <- lists:seq(1, X)]
41 %% ============================================================================
43 %% ============================================================================
55 ok = do_print_status(Bar, X, Y, N, GenCount, Time),
56 ok = do_print_board(Board),
58 {NewTime, NewBoard} = timer:tc(fun() -> next_generation(X, Y, Board) end),
59 NewState = State#state{board = NewBoard
60 ,gen_count = GenCount + 1
61 ,gen_duration = NewTime
64 timer:sleep(?INTERVAL),
68 do_print_status(Bar, X, Y, N, GenCount, TimeMic) ->
69 TimeSec = TimeMic / 1000000,
70 ok = io:format("~s~n", [Bar]),
72 "X: ~b Y: ~b CELLS: ~b GENERATION: ~b DURATION: ~f~n",
73 [X, Y, N, GenCount, TimeSec]
75 ok = io:format("~s~n", [Bar]).
78 do_print_board(Board) ->
79 CharLists = array:to_list(
97 ok = io:format("~s~n", [CharList])
103 state_to_char(0) -> ?CHAR_DEAD;
104 state_to_char(1) -> ?CHAR_ALIVE.
107 next_generation(W, H, Board) ->
112 Neighbors = filter_offsides(H, W, neighbors(X, Y)),
113 States = neighbor_states(Board, Neighbors),
114 LiveNeighbors = lists:sum(States),
115 new_state(State, LiveNeighbors)
124 new_state(1, LiveNeighbors) when LiveNeighbors < 2 -> 0;
125 new_state(1, LiveNeighbors) when LiveNeighbors < 4 -> 1;
126 new_state(1, LiveNeighbors) when LiveNeighbors > 3 -> 0;
127 new_state(0, LiveNeighbors) when LiveNeighbors =:= 3 -> 1;
128 new_state(State, _LiveNeighbors) -> State.
131 neighbor_states(Board, Neighbors) ->
132 [array:get(X, array:get(Y, Board)) || {X, Y} <- Neighbors].
135 filter_offsides(H, W, Coordinates) ->
136 [{X, Y} || {X, Y} <- Coordinates, is_onside(X, Y, H, W)].
139 is_onside(X, Y, H, W) when (X >= 0) and (Y >= 0) and (X < W) and (Y < H) -> true;
140 is_onside(_, _, _, _) -> false.
144 [{X + OffX, Y + OffY} || {OffX, OffY} <- offsets()].
148 [offset(D) || D <- directions()].
151 offset('N') -> { 0, -1};
152 offset('NE') -> { 1, -1};
153 offset('E') -> { 1, 0};
154 offset('SE') -> { 1, 1};
155 offset('S') -> { 0, 1};
156 offset('SW') -> {-1, 1};
157 offset('W') -> {-1, 0};
158 offset('NW') -> {-1, -1}.
162 ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].
166 array:map(fun(_, _) -> init_row(X) end, array:new(Y)).
170 array:map(fun(_, _) -> init_cell_state() end, array:new(X)).
174 crypto:rand_uniform(0, 2).
177 atom_to_integer(Atom) ->
178 list_to_integer(atom_to_list(Atom)).