August 23, 2024

P12 - Decode a run-length encoded list.

Given a run-length code list generated as specified in problem P10, construct its uncompressed version.

Example:

> p12:decode([{4,a},{1,b},{2,c},{2,a},{1,d},{4,e}]).
    [a,a,a,a,b,c,c,a,a,d,e,e,e,e]

erlang

%Decode a run-length encoded list.

-module(p12).
-export([decode/1]).

decode(Ls) ->
    lists:flatmap(fun({Value, Elem}) -> 
        fill(Value, Elem, [])
    end, Ls).

fill(0, _, Ls) -> 
    Ls;

fill(Value, Elem, Ls) ->
    fill(Value - 1, Elem, [Elem | Ls]).
Be first to comment
Leave a reply