6 -define(CHAR_DEAD, 32). % " "
7 -define(CHAR_ALIVE, 111). % "o"
8 -define(CHAR_BAR, 45). % "-"
10 -define(INTERVAL, 100).
13 %% ============================================================================
15 %% ============================================================================
18 [X, Y] = [atom_to_integer(A) || A <- Args],
19 {Time, Board} = timer:tc(fun() -> init_board(X, Y) end),
21 life_loop(X, Y, Generation, Time, Board).
24 %% ============================================================================
26 %% ============================================================================
28 life_loop(X, Y, Generation, Time, Board) ->
29 ok = do_print_status(X, Y, Generation, Time),
30 ok = do_print_board(Board),
32 {NextTime, NextBoard} = timer:tc(fun() -> next_generation(X, Y, Board) end),
33 NextGeneration = Generation + 1,
34 timer:sleep(?INTERVAL),
35 life_loop(X, Y, NextGeneration, NextTime, NextBoard).
38 do_print_status(X, Y, Generation, TimeMic) ->
39 TimeSec = TimeMic / 1000000,
40 Bar = [?CHAR_BAR || _ <- lists:seq(1, X)],
41 ok = io:format("~s~n", [Bar]),
43 "X: ~b Y: ~b CELLS: ~b GENERATION: ~b DURATION: ~f~n",
44 [X, Y, X * Y, Generation, TimeSec]
46 ok = io:format("~s~n", [Bar]).
49 do_print_board(Board) ->
50 CharLists = array:to_list(
68 ok = io:format("~s~n", [CharList])
74 state_to_char(0) -> ?CHAR_DEAD;
75 state_to_char(1) -> ?CHAR_ALIVE.
78 next_generation(W, H, Board) ->
83 Neighbors = filter_offsides(H, W, neighbors(X, Y)),
84 States = neighbor_states(Board, Neighbors),
85 LiveNeighbors = lists:sum(States),
86 new_state(State, LiveNeighbors)
95 new_state(1, LiveNeighbors) when LiveNeighbors < 2 -> 0;
96 new_state(1, LiveNeighbors) when LiveNeighbors < 4 -> 1;
97 new_state(1, LiveNeighbors) when LiveNeighbors > 3 -> 0;
98 new_state(0, LiveNeighbors) when LiveNeighbors =:= 3 -> 1;
99 new_state(State, _LiveNeighbors) -> State.
102 neighbor_states(Board, Neighbors) ->
103 [array:get(X, array:get(Y, Board)) || {X, Y} <- Neighbors].
106 filter_offsides(H, W, Coordinates) ->
107 [{X, Y} || {X, Y} <- Coordinates, is_onside(X, Y, H, W)].
110 is_onside(X, Y, H, W) when (X >= 0) and (Y >= 0) and (X < W) and (Y < H) -> true;
111 is_onside(_, _, _, _) -> false.
115 [{X + OffX, Y + OffY} || {OffX, OffY} <- offsets()].
119 [offset(D) || D <- directions()].
122 offset('N') -> { 0, -1};
123 offset('NE') -> { 1, -1};
124 offset('E') -> { 1, 0};
125 offset('SE') -> { 1, 1};
126 offset('S') -> { 0, 1};
127 offset('SW') -> {-1, 1};
128 offset('W') -> {-1, 0};
129 offset('NW') -> {-1, -1}.
133 ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].
137 array:map(fun(_, _) -> init_row(X) end, array:new(Y)).
141 array:map(fun(_, _) -> init_cell_state() end, array:new(X)).
145 crypto:rand_uniform(0, 2).
148 atom_to_integer(Atom) ->
149 list_to_integer(atom_to_list(Atom)).