Skip to content

Instantly share code, notes, and snippets.

@mokele
Created August 3, 2014 19:30
Show Gist options
  • Save mokele/cc78bfd4b578ddf474fb to your computer and use it in GitHub Desktop.
Save mokele/cc78bfd4b578ddf474fb to your computer and use it in GitHub Desktop.
-module(gos_geometry).
% run: io:format("~p~n", [gos_geometry:square(9)]).
%% API.
-export([square/1]).
-record(geometry_point, {id, neighbours}).
-spec square(pos_integer()) -> list(#geometry_point{}).
square(Size) ->
PointCount = Size * Size,
lists:map(fun(N) -> square_point(N, Size) end, lists:seq(0, PointCount - 1)).
square_point(N, Size) ->
#geometry_point{
id = N,
neighbours = square_point_neighbours(N, Size)
}.
left(N) -> N - 1.
right(N) -> N + 1.
up(N, Size) -> N - Size.
down(N, Size) -> N + Size.
square_point_neighbours(0, 1) ->
[];
square_point_neighbours(0 = N, Size) ->
[right(N), down(N, Size)]; % top left
square_point_neighbours(N, Size) when N < Size - 1 ->
[left(N), right(N), down(N, Size)]; % top
square_point_neighbours(N, Size) when N =:= Size - 1 ->
[left(N), down(N, Size)]; % top right
square_point_neighbours(N, Size) when N =:= Size*(Size-1) ->
[up(N, Size), right(N)]; % bottom left
square_point_neighbours(N, Size) when N =:= Size*Size-1 ->
[up(N, Size), left(N)]; % bottom right
square_point_neighbours(N, Size) when N rem Size =:= 0 ->
[up(N, Size), right(N), down(N, Size)]; % left
square_point_neighbours(N, Size) when N rem Size =:= Size - 1 ->
[up(N, Size), left(N), down(N, Size)]; % right
square_point_neighbours(N, Size) when N > Size*(Size-1) ->
[up(N, Size), left(N), right(N)]; % bottom
square_point_neighbours(N, Size) ->
[up(N, Size), left(N), right(N), down(N, Size)].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment