[erlang-questions] Speedy unsort:shuffle/1,2 ?

Johan Montelius johanmon@REDACTED
Thu May 27 10:33:01 CEST 2010


On Thu, 27 May 2010 10:10:53 +0200, Håkan Huss <huss01@REDACTED> wrote:

> randmerge([], 0, L2, _) ->
>    L2;
> randmerge(L1, _, [], 0) ->
>    L1;
> randmerge(L1, L1_len, L2, L2_len) ->
>    case random:uniform(L1_len + L2_len) of
>        N when N =< L1_len ->
>            [hd(L1) | randmerge(tl(L1), L1_len - 1, L2, L2_len)];
>        _ ->
>            [hd(L2) | randmerge(L1, L1_len, tl(L2), L2_len - 1)]
>    end.


Why use the length of the list? What is the advantage of using a coin-flip?

randmerge([], L2) ->
    L2;
randmerge(L1, []) ->
    L1;
randmerge(L1, L2) ->
    case random:uniform(2) of
        1 ->
            [hd(L1) | randmerge(tl(L1), L2)];
        2 ->
            [hd(L2) | randmerge(L1, tl(L2))]
    end.


-- 
Associate Professor Johan Montelius
Royal Institute of Technology - KTH
School of Information and Communication Technology - ICT


More information about the erlang-questions mailing list