erlang
erlang

Reputation: 273

How to count the occurrence of each character in a list?

How to count all consecutive repeated elements in a list and packs them together with the number of their occurrences as pairs.

Example :

compress("Hello") == [{1,$H},{1,$e},{2,$l},{1,$o}]

I have tried this function but I have errors, can someone help me to solve :

compress([])->
    [];
compress(L)->
    helper(L,0).

helper([], _)->
    [];
helper([H|T], Count)->
    case H == hd(T) of
        true -> helper(T,Count), [{Count+1, H}];
        false -> helper(T, Count), [{Count, H}]
    end.

Upvotes: 0

Views: 1032

Answers (1)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

This way:

compress(L) ->
    helper(L, []).

helper([], Acc) -> lists:reverse(Acc);
helper([H|T], [{Count, H}|Acc]) ->
    helper(T, [{Count+1, H}|Acc]);
helper([H|T], Acc) ->
    helper(T, [{1, H}|Acc]).

Or more straightforward and on some platforms faster (less garbage generating) version:

compress2([]) -> [];
compress2([H|T]) ->
    helper2(T, H, 1).

helper2([H|T], H, Count) ->
    helper2(T, H, Count+1);
helper2([H|T], C, Count) ->
    [{Count, C}|helper2(T, H, 1)];
helper2([], C, Count) ->
    [{Count, C}].

Upvotes: 1

Related Questions