Update README.
[cellular-automata.git] / life / 001 / src / life.erl
CommitLineData
d2a0e2f9
SK
1-module(life).
2-behaviour(application).
3
4
5%% API
6-export([bang/0]).
7
8%% Callbacks
9-export([start/2, stop/1]).
10
11
12-define(DIRECTIONS, ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']).
13
14
15%% ============================================================================
16%% API
17%% ============================================================================
18
19bang() ->
20 application:start(?MODULE).
21
22
23%% ============================================================================
24%% Callbacks
25%% ============================================================================
26
27start(_StartType, _StartArgs) ->
28 {ok, X} = application:get_env(?MODULE, x),
29 {ok, Y} = application:get_env(?MODULE, y),
30 CellData = cell_data(X, Y),
1aa9333c 31 life_god:start_link(X, Y, CellData).
d2a0e2f9
SK
32
33
34stop(_State) ->
35 ok.
36
37
38%% ============================================================================
39%% Internal
40%% ============================================================================
41
42cell_data(X, Y) ->
43 N = X * Y,
44 [cell_datum(X, N, ID) || ID <- lists:seq(1, N)].
45
46
47cell_datum(X, N, ID) ->
48 Name = integer_to_atom(ID),
49 NeighborNames = filter_offsides(N,
50 [integer_to_atom(neighbor_id(Dir, X, ID)) || Dir <- ?DIRECTIONS]
51 ),
52 {ID, Name, NeighborNames}.
53
54
55neighbor_id(Direction, X, ID) -> ID + offset(Direction, X).
56
57
58offset('N' , X) -> ensure_negative(X);
59offset('NE', X) -> ensure_negative(X - 1);
60offset('E' , _) -> 1;
61offset('SE', X) -> X + 1;
62offset('S' , X) -> X;
63offset('SW', X) -> X - 1;
64offset('W' , _) -> ensure_negative( 1);
65offset('NW', X) -> ensure_negative(X + 1).
66
67
68ensure_negative(N) when N < 0 -> N;
69ensure_negative(N) -> -(N).
70
71
72filter_offsides(N, IDs) ->
73 [ID || ID <- IDs, is_onside(N, atom_to_integer(ID))].
74
75
76is_onside(_, ID) when ID < 1 -> false;
77is_onside(N, ID) when ID > N -> false;
78is_onside(_, _) -> true.
79
80
81atom_to_integer(Atom) ->
82 list_to_integer(atom_to_list(Atom)).
83
84
85integer_to_atom(Integer) ->
86 list_to_atom(integer_to_list(Integer)).
This page took 0.036782 seconds and 4 git commands to generate.