August 23, 2024

P09 - Pack consecutive duplicates of list elements into sublists.

If a list contains repeated elements they should be placed in separate sublists.

Example:

> p09:pack(['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']).
    [[a,a,a,a],[b],[c,c],[a,a],[d],[e,e,e,e]]

erlang

%Pack consecutive duplicates of list elements into sublists.
%
-module(p09).
-export([pack/1]).

pack([H | T]) ->
    pack([], [], [H |T], H).

pack(FinalAns, AnsLs, [CurrH | CurrT], Elem) when CurrH == Elem ->
    pack(FinalAns, AnsLs ++ [Elem], CurrT, Elem);

pack(FinalAns, AnsLs, [CurrH | CurrT], Elem) ->
    pack(FinalAns ++ [AnsLs], [], [CurrH | CurrT], CurrH);

pack(FinalAns, AnsLs, [], _) ->
    FinalAns ++ [AnsLs].
Be first to comment
Leave a reply