Skip to content

Instantly share code, notes, and snippets.

@ngerakines
Created January 7, 2010 03:00
Show Gist options
  • Select an option

  • Save ngerakines/270934 to your computer and use it in GitHub Desktop.

Select an option

Save ngerakines/270934 to your computer and use it in GitHub Desktop.
-module(spiral).
-compile(export_all).
%% -- if accumulator is empty, put first row into acc and continue
%% -- if last accum value is first value of row 1, put row one into accum and continue
%% -- if last accum value is last value of row one, collect all last row values into accum and continue
%% -- if last accum value is last value of last row, collect last row into accum and continue
%% -- if last accume value is first value of last row, collect first values into accum and continue
follow2() ->
A = [
[01, 02, 03, 04, 05],
[14, 15, 16, 17, 06],
[13, 20, 19, 18, 07],
[12, 11, 10, 09, 08]
],
follow2(A, [0]).
follow2([FirstRow | Matrix], []) ->
follow2(Matrix, FirstRow);
follow2([], Acc) -> Acc;
follow2(Matrix, Acc) ->
LastVal = lists:max(Acc) + 1,
case LastVal == first_of_first(Matrix) of
true ->
[Row | Tail] = Matrix,
follow2(Tail, Acc ++ Row);
false ->
case LastVal == last_of_first(Matrix) of
true ->
{Values, NewMatrix} = last_values(Matrix),
follow2(NewMatrix, Acc ++ Values);
false ->
case LastVal == last_of_last(Matrix) of
true ->
[Values | Tail] = lists:reverse(Matrix),
follow2(lists:reverse(Tail), Acc ++ lists:reverse(Values));
false ->
case LastVal == first_of_last(Matrix) of
true ->
{Values, NewMatrix} = first_values(Matrix),
follow2(NewMatrix, Acc ++ lists:reverse(Values));
false ->
exit({{error, invalid_spiral_matrix}, erlang:get_stacktrace()})
end
end
end
end.
first_of_first([ [ Value | _ ] | _]) -> Value.
last_of_first([Row | _Matrix]) ->
[Value | _ ] = lists:reverse(Row),
Value.
last_of_last(Matrix) ->
[LastRow | _] = lists:reverse(Matrix),
[Value | _] = lists:reverse(LastRow),
Value.
first_of_last(Matrix) ->
[[Value | _] | _] = lists:reverse(Matrix),
Value.
last_values(Matrix) ->
last_values(Matrix, [], []).
last_values([], Values, Acc) -> {lists:reverse(Values), lists:reverse(Acc)};
last_values([Row | Matrix], Values, Acc) ->
[Value | RowTail] = lists:reverse(Row),
last_values(Matrix, [Value | Values], [lists:reverse(RowTail) | Acc]).
first_values(Matrix) ->
first_values(Matrix, [], []).
first_values([], Values, Acc) -> {lists:reverse(Values), lists:reverse(Acc)};
first_values([[Value | RowTail] | Matrix], Values, Acc) ->
first_values(Matrix, [Value | Values], [RowTail | Acc]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment