Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- % Enter your code here. Read input from STDIN. Print output to STDOUT
- % Your class should be named solution
- -module(solution).
- -export([main/0]).
- show_matrix(M) ->
- lists:foreach(fun(Row) ->
- lists:foreach(fun(E) ->
- io:format("~p ", [E])
- end, Row),
- io:format("~n",[])
- end, M).
- read_row(_) ->
- Line = io:get_line(""),
- LineWithoutNL = string:strip(string:strip(Line, both, 13), both, 10),
- StrNumbers = re:split(LineWithoutNL, "\s+", [notempty]),
- lists:map(fun erlang:list_to_integer/1, lists:map(fun erlang:binary_to_list/1,StrNumbers)).
- read_matrix(0, _, Acc) -> Acc;
- read_matrix(R, C, Acc) ->
- read_matrix(R - 1, C, Acc ++ [read_row(C)]).
- generate_rings(R, C) ->
- NRrings = min(R, C) div 2,
- lists:foldl(fun(Rn, Acc) ->
- Rows = R - (Rn - 1) * 2,
- Cols = C - (Rn - 1) * 2,
- LC = [{Rx, Rn}|| Rx <- lists:seq(Rn, Rn + Rows - 1)],
- RC = [{Rx, Rn + Cols - 1}|| Rx <- lists:seq(Rn + Rows - 1, Rn, -1)],
- TR = [{Rn, Cx} || Cx <- lists:seq(Rn + Cols - 2, Rn + 1, -1)],
- BR = [{Rn + Rows - 1, Cx} || Cx <- lists:seq(Rn + 1, Rn + Cols - 2)],
- Acc ++ [LC ++ BR ++ RC ++ TR]
- end, [], lists:seq(1, NRrings)).
- setnth(1, [_|Rest], New) -> [New|Rest];
- setnth(I, [E|Rest], New) -> [E|setnth(I-1, Rest, New)].
- matrix_get(M, R, C) ->
- lists:nth(C, lists:nth(R, M)).
- matrix_set(Mat, R, C, Value) ->
- Ro = lists:nth(R, Mat),
- Ru = setnth(C, Ro, Value),
- setnth(R, Mat, Ru).
- rotate_ring(M, Ring) ->
- {Lr, Lc} = lists:last(Ring),
- {RM, _} = lists:foldl(fun({Ur, Uc}, {Mat, Uvalue}) ->
- Nvalue = matrix_get(Mat, Ur, Uc),
- {matrix_set(Mat, Ur, Uc, Uvalue), Nvalue}
- end, {M, matrix_get(M, Lr, Lc)}, Ring),
- RM.
- rotate_matrix(M, Rings) ->
- lists:foldl(fun(Ring, Mat) ->
- rotate_ring(Mat, Ring)
- end, M, Rings).
- rotate(R, C, M, Rotations) ->
- Rings = generate_rings(R, C),
- RM = lists:foldl(fun(_, Mat) ->
- rotate_matrix(Mat, Rings)
- end, M, lists:seq(1,Rotations)),
- RM.
- main() ->
- {ok ,[R, C, Rotations]} = io:fread("", "~d ~d ~d"),
- Matrix = read_matrix(R, C, []),
- RMatrix = rotate(R, C, Matrix, Rotations),
- show_matrix(RMatrix).
Advertisement
Add Comment
Please, Sign In to add comment