Created
November 24, 2015 21:27
-
-
Save vjache/35a4e4b0d21ec161b524 to your computer and use it in GitHub Desktop.
Encode/Decode problem on Erlang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(codec). | |
-export([encode/1, decode/1]). | |
encode(Ss) -> | |
encode(Ss, ""). | |
encode([], Enc) -> | |
lists:reverse(Enc); | |
encode([ S | Ss ], Enc) -> | |
case S of | |
"" when Ss /= [] -> encode(Ss, ":" ++ Enc); | |
"" -> encode([], Enc); | |
"!" ++ S1 -> encode([ S1 | Ss ], "!!" ++ Enc); | |
":" ++ S1 -> encode([ S1 | Ss ], ":!" ++ Enc); | |
[C|S1] -> encode([ S1 | Ss ], [C|Enc]) | |
end. | |
decode(S) -> | |
decode(S, [""]). | |
decode(Str, [S | Ss] = Acc) -> | |
case Str of | |
"!!" ++ Tail -> decode(Tail, [ "!" ++ S | Ss ]); | |
"!:" ++ Tail -> decode(Tail, [ ":" ++ S | Ss ]); | |
":" ++ Tail -> decode(Tail, [ "", lists:reverse(S) | Ss ]); | |
[X|Tail] -> decode(Tail, [ [X|S] | Ss ]); | |
"" -> lists:reverse(Acc) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Algorithm is:
encode
decode
scan string from left to right