-module(roman).
-compile(export_all).
mapRoman(Num) ->
lists:foldl(fun(X, Y) -> Y ++ X end , "", lists:map(fun mapNum/1, subtractNum(Num))).
getActionResult({_Action, 0, _Src, _Dst}, Result) -> Result;
getActionResult({Action, N, Src, Dst}, Result) ->
Compute = fun(add, X, Y) -> X ++ Y;
(del, X, Y) -> Y ++ X end,
getActionResult({Action, N-1, Src, Dst}, Compute(Action, Result, Dst)).
subtractNum(Num) -> subtractNum(Num, 1000, []).
subtractNum(0, 0, Result) -> lists:reverse(Result);
subtractNum(Num, InitNum, Result) ->
SubNum = Num div InitNum,
ModNum = Num rem InitNum,
subtractNum(ModNum, InitNum div 10, [{SubNum, InitNum}|Result]).
mapNum({Num, Level}) ->
{Action, N, Src, Dst} = getPosAction(Num, Level),
getActionResult({Action, N, Src, Dst}, Src).
getPosAction(Num, Level) ->
Dict = #{ 1 => {"I", "V", "X"}, 10 => {"X", "L", "C"}, 100 => {"C", "D", "M"},
1000 => {"M", "", ""}},
{One, Five, Ten} = maps:get(Level, Dict, {"", "", ""}),
if
Num == 0 -> {add, 0, "", ""};
Num < 4 ->
{add, Num - 1, One, One};
Num >= 5 andalso Num < 9 ->
{add, Num - 5, Five, One};
Num == 4 ->
{del, 1, Five, One};
Num == 9 ->
{del, 1, Ten, One}
-compile(export_all).
mapRoman(Num) ->
lists:foldl(fun(X, Y) -> Y ++ X end , "", lists:map(fun mapNum/1, subtractNum(Num))).
getActionResult({_Action, 0, _Src, _Dst}, Result) -> Result;
getActionResult({Action, N, Src, Dst}, Result) ->
Compute = fun(add, X, Y) -> X ++ Y;
(del, X, Y) -> Y ++ X end,
getActionResult({Action, N-1, Src, Dst}, Compute(Action, Result, Dst)).
subtractNum(Num) -> subtractNum(Num, 1000, []).
subtractNum(0, 0, Result) -> lists:reverse(Result);
subtractNum(Num, InitNum, Result) ->
SubNum = Num div InitNum,
ModNum = Num rem InitNum,
subtractNum(ModNum, InitNum div 10, [{SubNum, InitNum}|Result]).
mapNum({Num, Level}) ->
{Action, N, Src, Dst} = getPosAction(Num, Level),
getActionResult({Action, N, Src, Dst}, Src).
getPosAction(Num, Level) ->
Dict = #{ 1 => {"I", "V", "X"}, 10 => {"X", "L", "C"}, 100 => {"C", "D", "M"},
1000 => {"M", "", ""}},
{One, Five, Ten} = maps:get(Level, Dict, {"", "", ""}),
if
Num == 0 -> {add, 0, "", ""};
Num < 4 ->
{add, Num - 1, One, One};
Num >= 5 andalso Num < 9 ->
{add, Num - 5, Five, One};
Num == 4 ->
{del, 1, Five, One};
Num == 9 ->
{del, 1, Ten, One}
end.
测试 "MDCCCLXXXVIII" = mapRoman(1888),