khalfella

rotate_matrix_erlang

Nov 30th, 2016
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. % Enter your code here. Read input from STDIN. Print output to STDOUT
  2. % Your class should be named solution
  3.  
  4. -module(solution).
  5. -export([main/0]).
  6.  
  7. show_matrix(M) ->
  8. lists:foreach(fun(Row) ->
  9. lists:foreach(fun(E) ->
  10. io:format("~p ", [E])
  11. end, Row),
  12. io:format("~n",[])
  13. end, M).
  14.  
  15. read_row(_) ->
  16. Line = io:get_line(""),
  17. LineWithoutNL = string:strip(string:strip(Line, both, 13), both, 10),
  18. StrNumbers = re:split(LineWithoutNL, "\s+", [notempty]),
  19. lists:map(fun erlang:list_to_integer/1, lists:map(fun erlang:binary_to_list/1,StrNumbers)).
  20.  
  21. read_matrix(0, _, Acc) -> Acc;
  22. read_matrix(R, C, Acc) ->
  23. read_matrix(R - 1, C, Acc ++ [read_row(C)]).
  24.  
  25.  
  26. generate_rings(R, C) ->
  27. NRrings = min(R, C) div 2,
  28. lists:foldl(fun(Rn, Acc) ->
  29. Rows = R - (Rn - 1) * 2,
  30. Cols = C - (Rn - 1) * 2,
  31. LC = [{Rx, Rn}|| Rx <- lists:seq(Rn, Rn + Rows - 1)],
  32. RC = [{Rx, Rn + Cols - 1}|| Rx <- lists:seq(Rn + Rows - 1, Rn, -1)],
  33. TR = [{Rn, Cx} || Cx <- lists:seq(Rn + Cols - 2, Rn + 1, -1)],
  34. BR = [{Rn + Rows - 1, Cx} || Cx <- lists:seq(Rn + 1, Rn + Cols - 2)],
  35. Acc ++ [LC ++ BR ++ RC ++ TR]
  36. end, [], lists:seq(1, NRrings)).
  37.  
  38.  
  39. setnth(1, [_|Rest], New) -> [New|Rest];
  40. setnth(I, [E|Rest], New) -> [E|setnth(I-1, Rest, New)].
  41.  
  42.  
  43. matrix_get(M, R, C) ->
  44. lists:nth(C, lists:nth(R, M)).
  45.  
  46. matrix_set(Mat, R, C, Value) ->
  47. Ro = lists:nth(R, Mat),
  48. Ru = setnth(C, Ro, Value),
  49. setnth(R, Mat, Ru).
  50.  
  51. rotate_ring(M, Ring) ->
  52. {Lr, Lc} = lists:last(Ring),
  53. {RM, _} = lists:foldl(fun({Ur, Uc}, {Mat, Uvalue}) ->
  54. Nvalue = matrix_get(Mat, Ur, Uc),
  55. {matrix_set(Mat, Ur, Uc, Uvalue), Nvalue}
  56. end, {M, matrix_get(M, Lr, Lc)}, Ring),
  57. RM.
  58.  
  59. rotate_matrix(M, Rings) ->
  60. lists:foldl(fun(Ring, Mat) ->
  61. rotate_ring(Mat, Ring)
  62. end, M, Rings).
  63.  
  64. rotate(R, C, M, Rotations) ->
  65. Rings = generate_rings(R, C),
  66. RM = lists:foldl(fun(_, Mat) ->
  67. rotate_matrix(Mat, Rings)
  68. end, M, lists:seq(1,Rotations)),
  69. RM.
  70.  
  71. main() ->
  72. {ok ,[R, C, Rotations]} = io:fread("", "~d ~d ~d"),
  73. Matrix = read_matrix(R, C, []),
  74. RMatrix = rotate(R, C, Matrix, Rotations),
  75. show_matrix(RMatrix).
Advertisement
Add Comment
Please, Sign In to add comment