Skip to content

Instantly share code, notes, and snippets.

@vjache
Created November 24, 2015 21:27
Show Gist options
  • Save vjache/35a4e4b0d21ec161b524 to your computer and use it in GitHub Desktop.
Save vjache/35a4e4b0d21ec161b524 to your computer and use it in GitHub Desktop.
Encode/Decode problem on Erlang.
-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.
@vjache
Copy link
Author

vjache commented Nov 24, 2015

Algorithm is:
encode

  1. perform substitution '!' -> "!!"
  2. perform substitution ':' -> "!:"
  3. join strings with ':'

decode
scan string from left to right

  1. "!!" -> "!"
  2. "!:" -> ":"
  3. ":" -> substring finished
  4. goto 1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment