Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
46
Task/Run-length-encoding/Erlang/run-length-encoding-1.erl
Normal file
46
Task/Run-length-encoding/Erlang/run-length-encoding-1.erl
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
-module(rle).
|
||||
|
||||
-export([encode/1,decode/1]).
|
||||
|
||||
-include_lib("eunit/include/eunit.hrl").
|
||||
|
||||
encode(S) ->
|
||||
doEncode(string:substr(S, 2), string:substr(S, 1, 1), 1, []).
|
||||
|
||||
doEncode([], CurrChar, Count, R) ->
|
||||
R ++ integer_to_list(Count) ++ CurrChar;
|
||||
doEncode(S, CurrChar, Count, R) ->
|
||||
NextChar = string:substr(S, 1, 1),
|
||||
if
|
||||
NextChar == CurrChar ->
|
||||
doEncode(string:substr(S, 2), CurrChar, Count + 1, R);
|
||||
true ->
|
||||
doEncode(string:substr(S, 2), NextChar, 1,
|
||||
R ++ integer_to_list(Count) ++ CurrChar)
|
||||
end.
|
||||
|
||||
decode(S) ->
|
||||
doDecode(string:substr(S, 2), string:substr(S, 1, 1), []).
|
||||
|
||||
doDecode([], _, R) ->
|
||||
R;
|
||||
doDecode(S, CurrString, R) ->
|
||||
NextChar = string:substr(S, 1, 1),
|
||||
IsInt = erlang:is_integer(catch(erlang:list_to_integer(NextChar))),
|
||||
if
|
||||
IsInt ->
|
||||
doDecode(string:substr(S, 2), CurrString ++ NextChar, R);
|
||||
true ->
|
||||
doDecode(string:substr(S, 2), [],
|
||||
R ++ string:copies(NextChar, list_to_integer(CurrString)))
|
||||
end.
|
||||
|
||||
rle_test_() ->
|
||||
PreEncoded =
|
||||
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",
|
||||
Expected = "12W1B12W3B24W1B14W",
|
||||
[
|
||||
?_assert(encode(PreEncoded) =:= Expected),
|
||||
?_assert(decode(Expected) =:= PreEncoded),
|
||||
?_assert(decode(encode(PreEncoded)) =:= PreEncoded)
|
||||
].
|
||||
20
Task/Run-length-encoding/Erlang/run-length-encoding-2.erl
Normal file
20
Task/Run-length-encoding/Erlang/run-length-encoding-2.erl
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
-module(rle).
|
||||
|
||||
-export([encode/1, decode/1]).
|
||||
|
||||
encode(L) -> encode(L, []).
|
||||
encode([], Acc) -> {rle, lists:reverse(Acc)};
|
||||
encode([H|T], []) ->
|
||||
encode(T, [{1, H}]);
|
||||
encode([H|T], [{Count, Char}|AT]) ->
|
||||
if
|
||||
H =:= Char ->
|
||||
encode(T, [{Count + 1, Char}|AT]);
|
||||
true ->
|
||||
encode(T, [{1, H}|[{Count, Char}|AT]])
|
||||
end.
|
||||
|
||||
decode({rle, L}) -> lists:append(lists:reverse(decode(L, []))).
|
||||
decode([], Acc) -> Acc;
|
||||
decode([{Count, Char}|T], Acc) ->
|
||||
decode(T, [[Char || _ <- lists:seq(1, Count)]|Acc]).
|
||||
Loading…
Add table
Add a link
Reference in a new issue