-module(fromroman).
-compile(export_all).
fromroman(RomanChar) ->
Pattern = "^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$",
{match, RomanList} = re:run(RomanChar, Pattern, [{capture, all_but_first, list}]),
NewRomanList = lists:zip(RomanList, [1000, 100, 10, 1]),
NumStr = lists:foldl(fun(X, Sum) -> Sum ++ X end, "", lists:map(fun mapNum/1, NewRomanList)),
list_to_integer(NumStr).
mapNum({"", _Level}) -> "0";
mapNum({Char, Level}) ->
SeqStr = "IVXLCDM",
Dict = #{ 1 => #{$I => 1, $V => 5, $X => 10},
10 => #{$X => 1, $L => 5, $C => 10},
100 => #{$C => 1, $D => 5, $M => 10},
1000 => #{$M => 1}},
CharDict = maps:get(Level, Dict),
MaxChar = lists:last(lists:usort(fun(X, Y)->
string:chr(SeqStr, X) =< string:chr(SeqStr, Y) end, Char)),
{DelList, AddList} = lists:splitwith(fun(Elem) -> Elem =/= MaxChar end, Char),
MapFun = fun(Chr) -> maps:get(Chr, CharDict) end,
integer_to_list(lists:sum(lists:map(MapFun, AddList)) - lists:sum(lists:map(MapFun, DelList))).